Inheritance in Java

Profile picture for user arilio666

Inheritance is the process where one class acquires properties and methods of another class. It is inheriting all traits from the parent to the child. The class which inherits properties is a subclass, aka a child class. Achieved using the "extends" keyword.

class parent{
method1{}
method2{}
}

Class child extends parent{
method3{}
}

child class = method1 from parent, method2 from parent and method3 from its own.

These are the types of inheritance:

  1. Single Inheritance
  2. Multilevel Inheritance
  3. Hierarchical Inheritance
  4. Multiple Inheritance
  5. Hybrid Inheritance

Single Inheritance

A class inherits properties and methods from only one parent class in single inheritance.

class Shinobi {
   void villageNative() {
       System.out.println("Leaf");
   }
}
class Naruto extends Shinobi {
   @Override
   void uzuInfo() {
       System.out.println("Uzumaki In Leaf Village");
   }
}
public class Main {
   public static void main(String[] args) {
      Naruto nar = new Naruto();
       nar.uzuInfo(); 
       nar.villageNative(); 
   }
}

Multiple Inheritance

Java does not support multiple-class inheritance, where a class can inherit properties and methods from more than one parent class. It will face compile time error.

class x{  
void msg(){System.out.println("John");}  
}  
class y{  
void msg(){System.out.println("Wick");}  
}  
class Z extends X,Y{//suppose if it were  
  
public static void main(String args[]){  
  Z obj=new Z();  
  obj.msg();  
}  
}  

Hierarchical Inheritance

In hierarchical inheritance, multiple classes inherit properties and methods from a single-parent class.

class x{  
void msg(){System.out.println("John");}  
}  
class y extends x{  
void name(){System.out.println("Wick");}  
}  
class z extends x{  
void anotherName(){System.out.println("Naruto");}  
}    
public static void main(String args[]){  
  Z obj=new Z();  
  obj.anotherName(); 
    obj.msg();
}  
}  

Multilevel Inheritance

When there is a chain of inheritance between classes, this is called multilevel inheritance.

class x{  
void msg(){System.out.println("John");}  
}  
class y extends x{  
void name(){System.out.println("Wick");}  
}  
class z extends y{  
void anotherName(){System.out.println("Naruto");}  
}    
public static void main(String args[]){  
  Z obj=new Z();  
  obj.anotherName(); 
    obj.msg();
    obj.name();
}  
}  

 
Tags