Wednesday 4 November 2015

Why abstract class can have constructor in Java?

Constructor in Abstract class

We cannot create instance of abstract class but we can declare constructor.

If we cannot make instance of abstract class why constructor allowed in abstract class?

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.

A constructor in Java doesn't actually "build" the object (new keyword is used to build an object), it is used to initialize fields.

abstract class Super {
      protected final String name;
      public Super(String name){
            this.name = name;
      }
      public abstract boolean printName();
}

class Child extends Super {
      public Child(String name) {
            super(name);
      }
      @Override
      public boolean printName() {
            System.out.println(this.name);
            return true;
      }
}

class AbstractConstructorTest {
      public static void main(String args[]) {
            Super supr = new Child("Child");
            supr.printName();
      }
}

Points to Note:

You should define all your constructors protected (making them public is pointless anyway because we cannot create object).

You may define more than one constructor (with different arguments).

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).

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...