Why do abstract classes in Java have constructors?

I am starting by clearing doubt of few techies that abstract classes do have constructor. Let us hear about few facts of abstract class.

  • Do abstract class have a constructor?
  • When abstract class constructor is called?

Yes, abstract class do have constructor.

It is called when its extending “concrete” class gets instantiated.

abstract class Vehicle { 
    int color;
	public Vehicle() {
	// TODO Auto-generated constructor stub
	}
}

class Car extends Vehicle {
	public Car() {
	//call to constructor of Vehicle abstract class (super())
	}
}

class MainClass{
	public static void main(){
		Car car = new Car();
	}
}

  • What does abstract class constructor do?
  • Why do abstract classes in Java have constructors?

Purpose of constructor is abstract classes may contain fields and sometimes they need to be initialized somehow by using constructor.

This chaining of constructors is one of the reasons abstract class can have constructors in Java.





  • Abstract class has fields X and Y
  • We want them to be initialized X and Y, no matter what actual concrete subclass is eventually created.
  • Create a constructor and initialize these fields X and Y in abstract class itself.
  • Constructor of abstract classes is called by super() of concrete extending class implicitly or explicitly.

Read More :- Difference in Interface of JAVA7, JAVA8 and JAVA9?

java 10 features value type







Leave a Reply

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