google.com, pub-8786015629279405, DIRECT, f08c47fec0942fa0 Write a Program to Implement Hierarchical Inheritance in Java

Write a Program to Implement Hierarchical Inheritance in Java

0
The relationships of objects or classes through inheritance give rise to a hierarchy. In hierarchical inheritance a single class serves as a super class (base class) for more than one sub class.


Syntax

Class A{
 public void methodA(){
  //Do Something
 }
}
Class B extends A{
 public void methodB(){
  //Do Something
 }
}
Class C extends A{
 public void methodC(){
  //Do Something
 }
}

Class MainClass{
 public void methodB(){
  //Do Something
 }
 public static void main(String args[]){
  B obj1 = new B();
  C obj2 = new C();
  obj1.methodA();
  obj2.methodA();
 }
}

Hierarchical Inheritance Example Program

class HierarchicalInheritance { 
 void DisplayA() { 
  System.out.println("This is a content of parent class"); 
 } 
} 

//B.java 
class A extends HierarchicalInheritance { 
 void DisplayB() { 
  System.out.println("This is a content of child class 1"); 
 } 
} 

//c.java 
class B extends HierarchicalInheritance { 
 void DisplayC() { 
  System.out.println("This is a content of child class 2"); 
 } 
} 

//MainClass.java 
class HierarchicalInheritanceMain { 
 public static void main(String args[]) { 
  System.out.println("Calling for child class C"); 
  B b = new B(); 
  b.DisplayA(); 
  b.DisplayC(); 
  System.out.println("Calling for child class B"); 
  A a = new A(); 
  a.DisplayA();
  a.DisplayB();
 } 
} 

Sample Output

Output is:
Calling for child class C
This is a content of parent class
This is a content of child class 2
Calling for child class B
This is a content of parent class
This is a content of child class 1



Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

Thank you for your interest 😊

We will back shortly after reviewing...

Thank you for your interest 😊

We will back shortly after reviewing...

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !
To Top