Explain inheritance with Examples.
Consider the example class Actor below:
public class Actor {
public void act(){
System.out.println("Act");
};
}
We can extend this class by using the keyword extends. Hero class extends Actor.
//IS-A relationship. Hero is-a Actor
public class Hero extends Actor {
public void fight(){
System.out.println("fight");
};
}
We can now create an instance of Hero class. Since Hero extends Animal, the methods defined in Animal are also available through an instance of Hero class. In the example below, we invoke the act method on hero object.
Hero hero = new Hero();
//act method inherited from Actor
hero.act();//Act
hero.fight();//fight
No Comments Yet!!