Java | Using Constructors in Inheritance.

We need to take care of only one thing while using Constructors in Inheritance. When we extend any class into the other class. It forces us to declare a similar constructor in the child class as well.

Usage of Constructors in Inheritance

  1. We can add constructor as we do normally without any return type.
  2. When we extend any class into the other class. It forces us to declare a similar constructor in the child class as well. (Feature of Inheritance)
  3. In the constructor of the child class, it automatically calls a constructor from its Parent class. This is done by using the ‘super’ keyword.
  4. Now, when we create an object of child class it automatically invokes the constructor of Parent class via its own constructor.
  5. We can also, declare multiple constructors in Parent class and the same can be called in the Child class as per requirement.
  6. At least one constructor should be added from the Parent class.

Code Example

Here we have create a Parent class “ClassA” having two parameterized constructors.

public class ClassA {
	int x;
	ClassA(int num)
		System.out.println("Value of x: "+x);
	ClassA(int x, int y)
		System.out.println("Constructor with 2 Parameters.");


Create another child class “ClassB” which extends the ClassA. As soon as we extend the Parent class we get a compile time error which forces us to add constructor of parent class into the child class.

public class ClassB extends ClassA{

	 * @param num
	  ClassB(int num) 
	 * @param x
	 * @param y
	ClassB(int x, int y) {
		super(x, y);
		// TODO Auto-generated constructor stub

	 * @param args
	public static void main(String[] args) 

            ClassB obj=new ClassB(5);

            ClassB obj1=new ClassB(3, 4);


Value of x: 5
Constructor with 2 Parameters.

OOPs Concept:

Java Basics:
Java Collection:

Java File Handling:

Java Question And Answer:

Java Programs:

Leave a Comment

Your email address will not be published. Required fields are marked *

   YouTube ChannelQuora

            Ashok Kumar is working in an IT Company as a QA Consultant. He has started his career as a Test Trainee in manual testing in August 2010. Then he moves towards the automation testing after 4 years. He started learning JAVA and Selenium by self to get the knowledge of automation.

       While learning these tools and working on multiple projects, he found that sometimes people get stuck in live scenarios in their project and they have to do lots of RnD to get out of it. So he decided to start blogging only for such scenarios, where anyone facing any problem in their project, can ask any question or give a solution or you can say an alternate solution to achieve the goal successfully.

Later on, he observed that some people want to learn Java but they have few questions in their mind like how to start Java, whether we should go for the online or offline course. So he started writing tutorials on Java, Jira, Selenium, Excel etc.