We want to avoid reusing things in code, Inheritance allows us to extend a class definition, keeping everything that was defined in a parent class and optionally adding some more fields / methods to a child class.
class Dog {
private int age;
private int weight;
private String color;
private String name;
public Dog(int age, int weight, String color, String name) {
this.age = age;
this.weight = weight;
this.color = color;
this.name = name;
}
public int getAge(){
return this.age
}
public void setAge(int age){
this.age = age
}
// etc...
}
class ShowDog extends Dog {
private int ranking
public ShowDog(int age, int weight, String color, String name, int ranking) {
super(age, weight, color, name);
this.ranking = ranking;
}
public int getRanking(){
return this.ranking;
}
public void setRanking(int ranking){
this.ranking = ranking;
}
}
Some notes on inheritance that trip people up:
super(...)
is a method used to call the constructor of your direct parent. If you are adding an extra parameter,you have to first initialize the parameters of the parent class and then initialize the extra parameter that only exists in the child. The super has to come first in the constructor.private
variables can't be accessed by the child class. Make sure to use setters and getters!