Java - Inheritance
In java, Inheritance is to reuse the Behaviors/methods and properties/state of some other class in your class.
Lets understand this with an example.
Story :
God has created human beings. So, he has prepared the 'Human' class with states and behaviours, so that human beings could be created based on the stated behaviour.
Now let's say there is a supreme God(more powerful than the God who created Humans). He had decided how all living beings should behave(Human, Animal, Fish).
So, he created 'LivingBeing' class.
class LivingBeing{
void breathe(){
System.out.println("Breathes oxygen from air.");
}
}
Story :
Now, he made this rule that all living beings, be it Human or Animal everyone should breathe oxygen from air.
So, the God who has created Human is not going to define the breathe() behaviour again. And he decided to reuse it.
Class Human extends LivingBeing{
String name;
String food;
String language;
Human(String nme, String fd, String lang){
this.name = nme;
this.food = fd;
this.language = lang;
}
public void eat(){
System.out.println("Eats "+food);
}
public void speak(){
System.out.println("Speaks "+language);
}
}
So, the Human creator God used the 'extends' keyword followed by the 'LivingBeing' class.
Class Human extends LivingBeing
Note :'extends' keyword says we are inheriting all the methods and properties of 'LivingBeing' class in 'Human' class.
And the breathe() behaviour of the 'LivingBeing' class becomes a part of 'Human' class. So, now along with eat() & speak() behaviour breathe() is also a method/behaviour of 'Human' class.
Now, let us write the class which creates the objects :
Class ApplicationTest{
public static void main(String[] arg){
Human human = new Human("Harry","Rice","Hindi");
human.eat();
human.speak();
human.breathe();
}
}
Output :
Eats Rice
Speaks Hindi
Breathes oxygen from air
In the above scenario with 'human' object of 'Human' class we are able to call the breathe() method as if it is a method of 'Human' class.