Inheritance

  • Inheritance is the process that enables one class to accquire the properties (method & variable ) of other.
  • With Inheritance , the information is placed in more manageable hierarchical order.
  • The class inherit the properties of another subclass (called as derived class or child class )  ,the class whose properties are inherited is the super class (base class or parent class ).
  • To inherit from a class , use the extends keyword.
  • Example
class Animal {
      protected int legs ; 
      public void eat(){
            System.out.println("Animal eats");
     }
}
class Dog extends Animal{
      Dog(){                           //constructor
          legs = 4;
       }
}
class Myclass{
      public static void main(String args[]){
             Dog d = new Dog();
             d.eat();
      }
}
  • As the Dog inherits the legs variables from the Animal class.
  • We can now declare a Dog Object & call the eat method in superclass.
  • The protected access modifier , which makes the member visible only to subclass.