Inheritance Example in Java

In this tutorial, we will write an Inheritance program in java. Before that, you should have knowledge on the following topic in Java.


Basic Example for Inheritance:

class Dog 
 {
  void dogName() 
  {
   System.out.println("My Name is Bruno");
  }
 }

 class Breed extends Dog 
 {
   void myBreed() 
   {
    System.out.println("German Shepard");
   }
 }

 public class Main 
 {
  public static void main(String args[]) 
  {
  Breed d = new Breed();
  d.dogName();
  d.myBreed();
  }
 }

Output:

My Name is Bruno
German Shepard


Example of Single Inheritance in Java:

 class SuperClass
 {
   public void methodSuper()
   {
     System.out.println("Super class method");
   }
 }

 class SubClass extends SuperClass
 {
   public void methodBase()
   {
     System.out.println("Sub class method");
   }
 }
 public class Main
 {
   public static void main(String args[])
   {
     SubClass s = new SubClass();
     s.methodSuper();
     s.methodBase();
   }
 }

Output:

Super class method
Base class method


Example of Multilevel Inheritance in Java:

class FirstClass
{
  public void displayFirst()
  {
    System.out.println("I am First Class");
  }
}

class SecondClass extends FirstClass
{
  public void displaySecond()
  {
    System.out.println("I am Second Class");
  }
}

class ThirdClass extends SecondClass
{
  public void displayThird()
  {
    System.out.println("I am Third Class");
  }
}

public class Main
{
  public static void main(String[] args)
  {
    ThirdClass three = new ThirdClass();
    three.displayFirst();
    three.displaySecond();
    three.displayThird();
  }
}

Output:

I am First Class
I am Second Class
I am Third Class


Example of Hierarchical Inheritance in Java:

class Animal
 {  
  void Dog()
  {
    System.out.println("I am dog");}  
 }  
    
 class Cat extends Animal
 {  
   void sleep()
   {
    System.out.println("I am Cat and I sleep");
   } 
 }

 class Horse extends Animal
 {  
   void run()
   {
    System.out.println("I am Horse and I run");
   }  
 }  

 public class Main
 {  
   public static void main(String args[])
   {  
    Horse h=new Horse();  
    h.Dog();  
    h.run();  
    
    Cat c=new Cat();  
    c.Dog();  
    c.sleep();
   }
        
 }

Output:

I am dog
I am Horse and I run
I am dog
I am Cat and I sleep