Inheritance Example Program in Java for Practice
In this tutorial, we have listed topic-wise the best collection of inheritance example program in Java with output and explanation.
These inheritance example programs are very important for Java interview purposes and technical test.
If you practice all these interview programs, then definitely, you can able to solve all questions based on Java inheritance. So, let’s start with simple program for practice.
Single Level Inheritance Program in Java
Let’s take a simple example program based on single inheritance in Java. In this example, we will create only one superclass and one subclass that will inherit instance method methodA() from the superclass. Look at the program code to understand better.
Example Program 1:
package inheritancePractice;
// Create a base class or superclass.
public class A
{
// Declare an instance method.
public void methodA()
{
System.out.println("Base class method");
}
}
// Declare a derived class or subclass and extends base class A.
public class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
}
public class Myclass {
public static void main(String[] args)
{
// Create an object of class B.
B obj = new B();
obj.methodA(); // methodA() of B will be called because by default, it is available in B.
obj.methodB(); // methodB() of B will be called.
}
}
Output:
Base class method
Child class method
Explanation:
In this example, we have defined a base class A which contains a single methodA() method. The statement “class B extends A” tells Java compiler that B is a new class inheriting from class A. This makes class A as the base class of class B and class B is known as a derived class.
In subclass B, we have defined one method methodB(). Subclass B contains inherited members ( methodA() ) of base class A and methodB(). In the main method, we have created an object of class B and invoked methods methodA() which is inherited from class A and methodB().
Multilevel Inheritance Program in Java
Let’s take a simple example program based on the multilevel inheritance in Java. Look at the program code and explanation.
Example Program 2:
package inheritancePractice;
public class X
{
public void methodX()
{
System.out.println("Class X method");
}
}
public class Y extends X
{
public void methodY()
{
System.out.println("Class Y method");
}
}
public class Z extends Y
{
public void methodZ()
{
System.out.println("Class Z method");
}
public static void main(String[] args)
{
Z z = new Z();
z.methodX(); // Calling X grand class method.
z.methodY(); // Calling Y parent class method.
z.methodZ(); // Calling Z class local method.
}
}
Output:
Class X method
Class Y method
Class Z method
Explanation:
In this example, we have defined a class X which is a parent class (or base class) for class Y (child class). Class Y is the parent class for class Z (child class).
Thus, class X is the grandfather of class Z (grandchild). The function methodY of class Y is inherited directly from class Y in class Z but the function methodX of class X is inherited indirectly from class X through class Y in class Z.
Hierarchical Inheritance Program in Java
Let’s take a very simple example program in which we will derive multiple subclasses such as B, C, and D from a single superclass A. All subclasses will inherit msgA() method from class A. Look at the program code to understand better.
Example Program 3:
package inheritancePractice;
public class A
{
public void msgA()
{
System.out.println("Method of class A");
}
}
public class B extends A
{
// Empty class B, inherits msgA of parent class A.
}
public class C extends A
{
// Empty class C, inherits msgA of parent class A.
}
public class D extends A
{
// Empty class D, inherits msgA of parent class A.
}
public class MyClass {
public static void main(String[] args)
{
// Create objects of classes B, C, and D.
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
// Calling inherited function from the base class.
obj1.msgA();
obj2.msgA();
obj3.msgA();
}
}
Output:
Method of class A
Method of class A
Method of class A
Behavior of Instance Variables in case of Inheritance
We know that instance variables are initialized at compile time. When an instance variable of the superclass is the same as that of the child class instance variable name, the “reference type” plays an important role to access instance variable. Let’s take an example program based on this concept.
Example Program 4:
package inheritancePractice;
public class P
{
// Declare an instance variable.
int a = 30;
}
public class Q extends P
{
// Declare an instance variable whose name is the same as that of the superclass instance variable name.
int a = 50;
}
public class Test extends Q {
public static void main(String[] args)
{
// Create an object of class Q and call the instance variable using reference variable q.
Q q = new Q();
System.out.println(" Value of a: " +q.a); // 'a' of Q is called.
// Declare superclass reference is equal to the child class object.
P p = new Q();
System.out.println("Value of a: " +p.a); // 'a' of P is called.
}
}Output:
Value of a: 50
Value of a: 30Explanation:
1. Inside the main() method, an object of class Q has been created. The reference variable q is pointing to the object of class Q.
2. Variable ‘a’ of Q is called because the reference variable for class Q has been created and is pointing to the object of class Q.
3. P p = new Q(); means the superclass reference variable is declared equal to the child class object.
4. Variable ‘a’ of P is called because, in the main() method, the reference variable for class P has been created but the object is created for the child class whereas, the object is referring itself to the superclass.
As the object is referring to the superclass at compile-time, Java compiler checks whether an instance variable is present or not in superclass.
If the instance variable is present in the superclass at the runtime, it will call the instance variable of the superclass.
Behavior of Overriding Method in case of Inheritance
Let’s take an example program to understand the behavior of overriding methods in the case of inheritance.
Example Program 5:
package inheritancePractice;
public class Baseclass
{
int x = 20;
// Overridden method.
void msg()
{
System.out.println("Base class method");
}
}
public class Childclass extends Baseclass
{
int x = 50;
int y = 100;
// Overriding method.
void msg()
{
System.out.println("Child class first method");
}
void msg2()
{
System.out.println("Child class second method");
}
}
public class MyTest extends Childclass {
public static void main(String[] args)
{
Childclass obj = new Childclass();
System.out.println("Value of x: " +obj.x); // x of class Childclass is called.
obj.msg(); // msg() of Childclass is called.
obj.msg2(); // msg2() of Childclass is called.
Baseclass obj2 = new Childclass();
System.out.println("Value of x: " +obj2.x); // x of Baseclass is called.
// System.out.println("Value of y: " +obj2.y); // Error because y does not exist in Baseclass.
obj2.msg(); // msg() of Childclass is called.
// obj2.msg2(); // Error because the method msg2() does not exist in Baseclass.
}
}Output:
Value of x: 50
Child class first method
Child class second method
Value of x: 20
Child class first methodExplanation:
1. Method overriding is only possible in the case of inheritance when the superclass method is overridden in its subclass. In the method overriding, method name, its argument type, the number of arguments, and return type must be the same.
[adinserter block=”2″]
2. The variable ‘x’ of Childclass is called because the object is created for the Childclass (subclass). The reference variable obj is pointing to the object of the child class.
3. When statement obj.msg() will be executed by JVM, msg() method of the child class is called because when any overridden method is called, it completely depends on the object through which it is called and the appropriate method call takes place according to this object. Since the object has been created for the child class, so msg() method of the child class will be called, not of a parent class.
4. The statement “Baseclass obj2 = new Childclass()” implies that the superclass reference variable is declared equal to the child class objects. In other words, the superclass reference variable holds the address of the created subclass objects. The reference variable ‘obj2’ is eligible to call only the members of a superclass.
5. When the statement obj2.msg() will be executed by JVM, msg() method of Childclass is called. This is because the object is created for the child class.
6. When obj2.x will be executed by JVM, variable “x” of Baseclass will be called because obj2 is the reference of Baseclass (superclass).
7. The statement obj2.y; an error will occur because variable “y” does not exist in Baseclass.
8. When obj2.msg(); will be executed, msg() of Childclass will be called because the object has been created for Childclass (subclass).
9. On the execution of obj2.msg2();, an error will occur because msg2() is a newly created method in Childclass. Therefore, we cannot access the newly created method by creating the reference of super class and pointing to the object of subclass.
Let’s take another example program based on the behavior of overriding method in case of inheritance.
Example Program 6:
package inheritancePractice;
public class Hello
{
// Declare an instance block.
{
show();
}
Hello()
{
System.out.println("Hello constructor");
show();
}
void show()
{
System.out.println("Hello method");
}
}
public class Hi extends Hello
{
Hi()
{
System.out.println("Hi constructor");
}
// Override the show() method.
void show() {
System.out.println("Hi method");
}
}
public class TestHelloHi extends Hi {
public static void main(String[] args)
{
Hi obj = new Hi();
obj.show(); // show() method of Hi class is called.
// Superclass reference is equal to child class object.
Hello obj1 = new Hi();
obj1.show();
}
}Output:
Hi method
Hello constructor
Hi method
Hi constructor
Hi method
Hi method
Hello constructor
Hi method
Hi constructor
Hi methodExplanation:
1. Inside the main method,
a. When an object of class Hi will create, the constructor of class Hi will be called immediately. But, the super keyword present in the first line of class Hi will call its parent class Hello. Since the instance block is present in the parent class, it will be executed first before the execution of parent class constructor and calls the show() method.
Since the show() method has been overridden in the child class, therefore, show() method of class Hi will be called. Hence, the output will be “Hi method”.
b. After executing the instance block, the constructor of the parent class will be executed. The output will be “Hello constructor”.
c. Inside the parent class constructor, the show() method of class Hi will be called. So, the output is “Hi method” because the object is created for the child class Hi.
d. After execution of complete parent class constructor, the constructor of Hi (child class) will be called.
2. The show() method of class Hi is called because the object is created for the child class.
3. The output will be the same for lines Hello obj1 = new Hi(); and obj1.show();.
Behavior of Overloaded Method in Inheritance
Method overloading is done at the compile time. Therefore, an appropriate method is invoked according to the reference type to call an overloaded method. Let’s take an example program to clarify this.
Example Program 7:
package inheritancePractice;
public class Animal
{
void food()
{
System.out.println("What kind of food do lions eat?");
}
}
public class Lion extends Animal
{
void food(int x)
{
System.out.println("Lions eat flesh");
}
}
public class LionTest extends Lion
{
public static void main(String[] args)
{
Animal a = new Lion();
a.food(); // food() method of class Animal is called.
// a.food(20); // Compile time error.
Lion l = new Lion();
l.food(); // food() method of class Lion is called.
l.food(10); // food() method of class Lion is called.
}
}Output:
What kind of food do lions eat?
What kind of food do lions eat?
Lions eat fleshExplanation:
1. The statement Animal a = new Lion(); implies that ‘a’ is the reference of the parent class whereas an object is created for the child class. When a.food(); is executed, food() method is called through the reference type ‘a’.
At the compile-time, the compiler checks the food() signature in the parent class. If the food() method is not overridden in the child class, it will call the parent class method at runtime. That’s why the output is “What kind of food do lions eat?”.
2. When the line a.food(20); is executed, it will give compile-time error. This is because the parent class Animal does not have a food method that takes an integer argument.
3. When the statement l.food(); will be executed, the food() method of class Lion will be called because the reference variable l is a type of Lion that is a subclass. The food() method of Animal class is available in Lion class through inheritance. Therefore, the output is “What kind of food do lions eat?”.
4. When l.food(20); will be executed, the food(int x) method of class Lion will be called. The output is “Lions eat flesh”.
Key Points:
1. At the compile time, an object reference variable plays an important role to call the method.
2. At runtime, the type of object created plays an important role to call the method.
Scenarios Based Program in Inheritance
Consider the below scenarios.
In this example program, we will create a superclass called AA and one subclass of it, called BB. Superclass AA declares two variables x, y, and two methods named msg1(), and msg2(). The subclass overrides one variable y and one method msg2() declared in AA. It also declares one variable z and one method named msg3().
Example Program 8:
package inheritancePractice;
public class AA
{
int x = 20;
int y = 30;
void msg1()
{
System.out.println("I am msg1 in class AA");
}
void msg2()
{
System.out.println("I am msg2 in class AA");
}
}
package inheritancePractice;
public class BB extends AA
{
int y = 50;
int z = 60;
// Overriding method.
void msg2()
{
System.out.println("I am msg2 in class BB");
}
void msg3()
{
System.out.println("I am msg3 in class BB");
}
}Only change the below class for all types of below scenarios.
Scenario 1:
In this scenario, there is a class Scenario1. Inside the main() method, an object of class AA is created and calls the variables and methods by using the object reference variable.
package inheritancePractice;
public class Scenario1 {
public static void main(String[] args)
{
// Scenario 1.
// Create an object of class AA.
// Here, 'a' is a reference variable of class A and pointing to the object of class AA.
// Therefore, superclass object reference a is eligible to call only A.
AA a = new AA();
System.out.println("Value of x: " +a.x); // x of class AA is called.
System.out.println("Value of y: " +a.y); // y of class AA is called.
// System.out.println("Value of z: " +a.z); // Error because z does not exist in AA.
// Call msg1() and msg2() methods using reference variable a.
a.msg1(); // msg1 of class AA is called.
a.msg2(); // msg2 of class AA is called.
// a.msg3(); //Error because the method msg3 does not exist in AA.
}
}Output:
Value of x: 20
Value of y: 30
I am msg1 in class AA
I am msg2 in class AAScenario 2:
package inheritancePractice;
public class Scenario2 {
public static void main(String[] args)
{
// Create an object of class BB.
// Here, 'b' is a reference variable of class BB and pointing to the object of class BB.
BB b = new BB();
// x of class BB is called because, by default, x of class AA is available in class BB through inheritance.
System.out.println("Value of x: " +b.x);
// y of class BB is called, not of class AA because the object is created for class BB.
System.out.println("Value of y: " +b.y);
System.out.println("Value of z: " +b.z); // z of class BB is called.
b.msg1(); // msg1 of class BB is called because it is available in class BB by default.
b.msg2(); // msg2 of class BB is called, not of class AA because an object is created for class BB.
b.msg3();
}
}Output:
Value of x: 20
Value of y: 50
Value of z: 60
I am msg1 in class AA
I am msg2 in class BB
I am msg3 in class BBScenario 3:
package inheritancePractice;
public class Scenario3 {
public static void main(String[] args)
{
// Superclass reference is equal to child class object.
AA a = new BB(); // 'a' is a reference variable of class AA but pointing to the object of class BB.
System.out.println("Value of x: " +a.x); // x of class AA is called.
System.out.println("Value of y: " +a.y); // y of class AA is called.
// System.out.println("Value of z: " +a.z); // Error because z does not exist in AA.
a.msg1(); // msg1 of class BB is called because it is available by default in class BB.
a.msg2(); // The overridden msg2 of class BB is called because an object is created for class BB.
// The commenting statement will generate an error
// because msg3 does not exist in AA. msg3() is a newly created method in class BB
// that cannot be called by using the reference variable 'a' of superclass and pointing to the object of subclass.
// a.msg3();
}
}Output:
Value of x: 20
Value of y: 30
I am msg1 in class AA
I am msg2 in class BBScenario 4:
package inheritancePractice;
public class Scenario4 {
public static void main(String[] args)
{
AA a = new AA();
BB b = new BB();
a = b;
System.out.println("Value of x: " +a.x);
System.out.println("Value of y: " +a.y);
// System.out.println("Value of z: " +a.z); // Error because z does not exist in class AA.
a.msg1();
a.msg2();
// a.msg3(); // Error msg3 of class AA not exist.
}
}Output:
Value of x: 20
Value of y: 30
I am msg1 in class AA
I am msg2 in class BBScenario 5:
package inheritancePractice;
public class Scenario5 {
public static void main(String[] args)
{
BB b = new AA(); // Syntax error. // Try calling everything by using b.
}
}Scenario 6:
package inheritancePractice;
public class Scenario6 {
public static void main(String[] args)
{
AA a = new BB();
BB b = new BB();
b = (BB)a; // It looks like a superclass assigned to a subclass, but it translates internally to
// BB b = new BB(); // It is equivalent to the 2nd scenario.
System.out.println("Value of x: " +a.x);
System.out.println("Value of y: " +a.y);
// System.out.println("Value of z: " +a.z); // Error because z does not exist in class AA.
a.msg1();
a.msg2();
// a.msg3(); // Compilation error.
}
}Output:
Value of x: 20
Value of y: 30
I am msg1 in class AA
I am msg2 in class BBHere, we have covered almost all the variety of inheritance example program in Java with explanations that you must practice before going for the technical interview. All the inheritance program are very important in Java for freshers and experienced level interviews. Keep in mind all the above concepts.
Thanks for reading!!!









