Why Abstract Classes have Constructors?

 
Many of you would always have a question on your mind that if we can’t instantiate the abstract classes then why do we have constructors of the same. Well, obviously.

But actually what happens. A constructor in Java doesn’t actually “build” the object, it is used to initialize fields.Imagine that your abstract class has fields x and y, and that you always want them to be initialized in a certain way, no matter what actual concrete subclass is eventually created.

So you create a constructor and initialize these fields.Now, if you have two different subclasses of your abstract class, when you instantiate them their constructors will be called, and then the parent constructor will be called and the fields will be initialized.

If you don’t do anything, the default constructor of the parent will be called. However, you can use the super keyword to invoke specific constructor on the parent class.


Copy the code given below, run it. And then see what the output is.

abstract class A1
{
	A1()
	{
		System.out.println("Hi I am in abstract class");
	}

}
class  A extends A1
{
	A()
	{
                //super(); implicitly called. Remove the comments and check
		System.out.println("Hi! I am called!" );
	}
	public void show(){
		System.out.println("Hello!");
	}
}

public class B
{
	public static void main(String args[])
	{
		A a1=new A();
		a1.show();
	}
}

Output
Hi! I am in abstract class
Hi! I am called!
Hello!

Simply, it may not be getting accessed directly but indirectly through it’s subclasses. There is just not the only thing you see is happening. There are other ways of implementation that has to be worked upon to keep the way the Java Programming language works.

Advertisements

One thought on “Why Abstract Classes have Constructors?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s