Java: Inheritance
Inheritance is basically inheriting variables and various things from a base class.
For example lets say we had some foods, and we wanted them all to have a hot and cold function, instead of copying and pasting these into each class, and then maintaining them afterwards; We can simple create a base class which has these functions, and then tell the different classes of food to inherit them.
We can achieve inheritance by using the "extends" keyword, for example:
class Food{
private boolean FoodHot;
void MakeFoodHot(){
FoodHot = true;
}
void MakeFoodCold(){
FoodHot = false;
}
void IsFoodHot(){
if(FoodHot==true){
System.out.println("The food is hot!");
} else if(FoodHot==false){
System.out.println("The food is cold..");
} else {
System.out.println("Unspecified...");
}
}
};
class FishAndChips extends Food{
};
public class Main {
public static void main(String[] args) {
FishAndChips Meal1 = new FishAndChips();
Meal1.MakeFoodHot()
Meal1.IsFoodHot();
Meal1.MakeFoodCold();
Meal1.IsFoodHot();
}
}
You can see its all pretty obvious, however at the moment all this is doing is making things easy, inheritance can do much more than that.For example we can override the base class functions with ones in the derived classes if we wanted; for example lets say we wanted to add a sandwich, because a sandwich is never going to get hot, lets change its functions a bit:
class Food{
private boolean FoodHot;
void MakeFoodHot(){
FoodHot = true;
}
void MakeFoodCold(){
FoodHot = false;
}
void IsFoodHot(){
if(FoodHot==true){
System.out.println("The food is hot!");
} else if(FoodHot==false){
System.out.println("The food is cold..");
} else {
System.out.println("Unspecified...");
}
}
};
class FishAndChips extends Food{};
class Sandwich extends Food{
void IsFoodHot(){
System.out.println("The food is cold!");
}
};
public class Main {
public static void main(String[] args) {
FishAndChips Meal1 = new FishAndChips();
Meal1.MakeFoodHot();
Meal1.IsFoodHot();
Meal1.MakeFoodCold();
Meal1.IsFoodHot();
System.out.println();
Sandwich Meal2 = new Sandwich();
Meal2.MakeFoodHot();
Meal2.IsFoodHot();
Meal2.MakeFoodCold();
Meal2.IsFoodHot()
}
}
Back to Java

