Skip to main content

Practical-23

Write a java program which explains the concept of Hierarchical Inheritance.

Introdution

Hierarchical Inheritance is a feature of object-oriented programming that helps to classify objects into main classes and subclasses. This type of inheritance allows a base class to become the parent of multiple subclasses which inherits its properties from the parent class. In Java, this type of inheritance is used to create a simple and easy relationship between classes and objects.

Code

class BaseClass {
public void baseMethod() {
System.out.println("Base Class Method");
}
}
class SubClass1 extends BaseClass {
public void sub1Method() {
System.out.println("Sub Class 1 Method");
}
}
class SubClass2 extends BaseClass {
public void sub2Method() {
System.out.println("Sub Class 2 Method");
}
}
public class Main {
public static void main(String[] args) {
SubClass1 obj1 = new SubClass1();
obj1.baseMethod();
obj1.sub1Method();
SubClass2 obj2 = new SubClass2();
obj2.baseMethod();
obj2.sub2Method();
}
}

Output

Base Class Method
Sub Class 1 Method
Base Class Method
Sub Class 2 Method

Explanation

This program defines a base class and two sub classes which inherits the base class. It then creates two objects of the subclass and calls a base class function and a function of the respective classes. :::