+92 332 4229 857 99ProjectIdeas@Gmail.com

Inheritance In Java Classes


Inheritance:
Inheritance is a mechanism in Java that allows you to extend a class with another class. In Java, Inheritance “is a” relationship i.e., teacher is a employee see below code example of inheritance.



Create a new class as an extension of another class to make it more powerful. That is, the derived class inherits the public methods and public data of the base class. Java only allows a class to have one immediate base class means no multiple inheritance i.e., single class inheritance.

For example:  

public class Employee {
       private int id;
       private String name;
             
         //parameterized constructor
         public Employee(int id, String name){

             this.id = id;
             this.name = name;
         }

         //default constructor
         public Employee(){
                id = 10;
                name = "not set";
         }
        
         public void display(){
             System.out.println("Employee id:" + id + " name:" + name);
         }
}

public class Teacher extends Employee {//here Teacher extending(inheriting) the Employee class

   private String qualification;

   //default constructor
   public Teacher () {
        //implicit call to superclass default constructor          
        qualification = "";     
   }

   //parameterized constructor
   public Teacher(int id, String name, String qual){
       super(id,name); //call to superclass(Employee) constructor must be in first line       
       qualification = qual;
   }
  
  
   public void displayResult(){
  
         super.display(); //call to superclass(Employee) display method
         System.out.println("Qualifications :" + qualification);
   }

}

public class Test {

       public static void main(String[] args) {
             
         System.out.println("Making Object Of Employee Class");
         Employee employee = new Employee(10, "Rehan Ali");  
        
  employee.display(); //call to Employee class display method
            
         System.out.println("Making Object Of Teacher Class");
         Teacher teacher = new Teacher (12, "Ali Haider", "Mcs");
          
         teacher.displayResult(); //call to Teacher class displayResult method

     }
}

Output:

Making Object Of Employee Class
Employee Id:10 name:Rehan Ali

Making Object Of Teacher Class
Employee Id:12 name:Ali Haider
Qualifications : Mcs

0 comments: