-
Notifications
You must be signed in to change notification settings - Fork 2
Java Inheritance Basics
So great you have successfully created a Car class. But, wait, aren't Tesla cars supposed to be electric variants? I want an Electric car class, but it also should have the properties of the original Car
class.
Solution : Inheritance. Java provides a neat way to "inherit" parent properties :
public class Car {
private String name;
private String manufacturerName;
public Car(String name, String man) {
this.name = name;
this.manufacturerName = man;
}
// Getter method
public String getName() {
return name;
}
// Getter method
public String getManufacturerName() {
return manufacturerName;
}
}
public class ElectricCar extends Car {
public ElectricCar(String name, String man) {
super(name, man);
}
public void charge() {
System.out.println("Charging ...");
}
}
ElectricCar modelS = new ElectricCar("Model S","Tesla");
// prints Tesla
System.out.println(modelS.getManufacturerName());
// prints Charging ...
modelS.charge();
🚀 Run Code
See here that the class ElecticCar
inherits or extends
the public methods from Car
class, as well as has its own methods and properties. Cool way to pass on information!
Also notice the usage of super keyword here. Since our Car
class had a constructor, so we have to initialize that constructor from the child class as well. We do that using the super
keyword. Read more about Inheritance here.
Learn to code and help nonprofits. Join our open source community in 15 seconds at http://freecodecamp.com
Follow our Medium blog
Follow Quincy on Quora
Follow us on Twitter
Like us on Facebook
And be sure to click the "Star" button in the upper right of this page.
New to Free Code Camp?
JS Concepts
JS Language Reference
- arguments
- Array.prototype.filter
- Array.prototype.indexOf
- Array.prototype.map
- Array.prototype.pop
- Array.prototype.push
- Array.prototype.shift
- Array.prototype.slice
- Array.prototype.some
- Array.prototype.toString
- Boolean
- for loop
- for..in loop
- for..of loop
- String.prototype.split
- String.prototype.toLowerCase
- String.prototype.toUpperCase
- undefined
Other Links