Explanation
This Java code demonstrates a concept called Hierarchical Inheritance. In this type of inheritance, a single parent class is inherited by multiple child classes.
Let's break down the code:
-
ClassA: This is the base class or parent class. It contains a single public methoddispA()which simply prints "disp() method of ClassA" to the console. -
ClassB: This is a child class thatextends ClassA. This meansClassBinherits all public and protected members (methods and variables) fromClassA. In addition to the inheriteddispA()method,ClassBdefines its own unique methoddispB(), which prints "disp() method of ClassB". -
ClassC: Similar toClassB,ClassCalsoextends ClassA. It's another child class ofClassA. It has its own unique methoddispC()that prints "disp() method of ClassC", and it also inheritsdispA()fromClassA. -
ClassD: Yet another child class thatextends ClassA. It defines its own methoddispD()which prints "disp() method of ClassD", and it also inheritsdispA()fromClassA. -
HierarchicalInheritanceTest: This is the main class where the program execution begins.- Inside the
mainmethod, an objectbofClassBis created. b.dispB()calls the method defined withinClassB.b.dispA()calls the method inherited fromClassA. This demonstrates thatClassBobjects have access toClassA's methods.- Next, an object
cofClassCis created. c.dispA()calls the method inherited byClassCfromClassA.ClassCobjects also have access toClassA's methods.- Finally, an object
dofClassDis created. d.dispD()calls the method defined withinClassD.d.dispA()calls the method inherited byClassDfromClassA.ClassDobjects similarly have access toClassA's methods.
- Inside the
The core logic is to show that ClassB, ClassC, and ClassD are all independent child classes deriving from the same parent, ClassA, and thus each can access ClassA's methods while also having their own unique functionalities.