Sunday, 24 April 2016

What is the use of constructor in Abstract class ?


We can declare constructor in Abstract class.
If we cannot make instance of abstract class why constructor allowed in abstract class?

It is used to perform some initialization (of the fields of abstract class) before the instantiation of a subclass.

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

Example
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();
      }
}


Notes
  • You should define all your constructors protected because there is no point making them public as you cannot create the object.
  • You can have overloaded constructors.
  • Your subclass constructor(s) can call one constructor of the abstract class.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.