The UML diagram bellow shows an example for simple chain of inheritance relationship where ClassC inherits ClassB’s members, including the ones that ClassB inherited from ClassA. ClassA constructor has a println statement that prints "Hello This is ClassA", ClassB constructor has a println statement that prints "Hello this is ClassB" and ClassC constructor has a println statement that prints "Hello this is ClassC". ClassC is the driver class. If you create an object of ClassC,you will get the following output: Hello this is ClassA Hello this is ClassB Hello this is ClassC Now write a Java program that meets above conditions.
Program:
//Program to be saved as ClassC.java
//classA
class ClassA
{
//constructor of ClassA
public ClassA()
{
//println statement in the
constructor
System.out.println("Hello this is
ClassA");
}
}
//classB that extends classA
class ClassB extends ClassA
{
//constructor of ClassB
public ClassB()
{
//println statement in the
constructor
System.out.println("Hello this is
ClassB");
}
}
////classC that extends classB, this our driver class also
public class ClassC extends ClassB
{
//constructor of ClassC
public ClassC()
{
//println statement in the
constructor
System.out.println("Hello this is
ClassC");
}
//driver program
public static void main(String[] args)
{
//create an object for classC
ClassC obj=new ClassC();
//creating an object for ClassC
calls the constructors of the parent class
//along with its own constructor
and prints all the statements
}
}
Output:
Get Answers For Free
Most questions answered within 1 hours.