JavaTip : An abstract class cannot be instantiated then why does it have the constructor

You would define a constructor in an abstract class if you are in one of these situations:

  • you want to perform some initialization (to fields of the abstract class) before the instantiation of a subclass actually takes place
  • you have defined final fields in the abstract class but you did not initialize them in the declaration itself; in this case, you MUST have a constructor to initialize these fields

Note that:

  • you may define more than one constructor (with different arguments)
  • you can (should?) define all your constructors protected (making them public is pointless anyway)
  • your subclass constructor(s) can call one constructor of the abstract class; it may even have to call it (if there is no no-arg constructor in the abstract class)

In any case, don’t forget that if you don’t define a constructor, then the compiler will automatically generate one for you (this one is public, has no argument, and does nothing).

An abstract class defines a common message protocol and a common set of instance variables for its subclasses. The point of having an abstract class is to avoid code duplication and to promote reuse. An abstract class cannot be instantiated, hence the name ‘abstract’. The constructor of an abstract class is used within the constructors of its subclasses (using the keyword ‘super’) to initialize the instance variables inherited from the abstract class.

Whether the parent class is abstract or not, calling its constructor within the child class’ constructor will not create a separate object. The operations performed by the parent constructor will be performed on/by the child object under construction.

Calling constructor not mean create object every time although creating object always call constructor.
Constructors do not create objects. They initialize objects. The ‘new’ operator creates objects.

Every class internally extends Object class by default. So, If abstract class doesn’t contain constructor we cannot access Object class constructor or we cannot create constructor for our subclasses.

 

package com.premaseem.commandPattern;

abstract class Product {
    int multiplyBy;
     Product( int multiplyBy ) {
        this.multiplyBy = multiplyBy;
    }
}

class TimesTwo extends Product {
    public TimesTwo() {
        super(2);
    }
}

class TimesWhat extends Product {
    public TimesWhat(int what) {
        super(what);
    }
}

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