oop Inheritance Example - Consider below two classes


Example

Teacher Class:

class Teacher {
       private String name;
       private double salary;
       private String subject;
       public Teacher (String tname)  {
           name = tname;
       }
       public String getName()  {
           return name;
       }
       private double getSalary()  {
           return salary;
       }
       private String  getSubject()  {
            return  subject;
       }
    }

OfficeStaff Class:

class  OfficeStaff{
   private String name;
   private double salary;
   private String dept;
   public OfficeStaff (String sname)  {
      name = sname;
   }
   public String getName()  {
       return name;
   }
   private double  getSalary()  {
       return salary;
   }
   private String  getDept ()  {
       return dept;
   }
}
  1. Both the classes share few common properties and methods. Thus repetition of code.
  2. Creating a class which contains the common methods and properties.
  3. The classes Teacher and OfficeStaff can inherit the all the common properties and methods from below Employee class.

Employee Class:

class Employee{
   private String name;
   private double salary;
   public Employee(String ename){
      name=ename;
   }
   public String getName(){
      return name;
   }
   private double getSalary(){
      return salary;
   } 
}
  1. Add individual methods and properties to it Once we have created a super class that defines the attributes common to a set of objects, it can be used to create any number of more specific subclasses
  2. Any similar classes like Engineer, Principal can be generated as subclasses from the Employee class.
  3. The parent class is termed super class and the inherited class is the sub class
  4. A sub class is the specialized version of a super class – It inherits all of the instance variables and methods defined by the super class and adds its own, unique elements.
  5. Although a sub class includes all of the members of its super class it can not access those members of the super class that have been declared as private.
  6. A reference variable of a super class can be assigned to a reference to any sub class derived from that super class i.e. Employee emp = new Teacher();