0

We cannot instantiate an abstract class but an abstract class can contain constructors.

Then what is the purpose of constructor in an abstract class?

a Learner
  • 4,608
  • 9
  • 46
  • 87

5 Answers5

1

We can instantiate instances of an abstract class to the extent that concrete sub-classes are instantiable. And when they are instantiated, the JVM will invoke the super() constructor. For example, if you were to try this

public abstract class Base {
  protected Base() {
    System.out.println("Base");
  }
}

public class Concrete extends Base {
  public Concrete() {
    System.out.println("Concrete");
  }
  public static void main(String[] args) {
    new Concrete();
  }
}

You would see

Base
Concrete
Elliott Frisch
  • 183,598
  • 16
  • 131
  • 226
1

Constrcutors are used, mainly, to initialize data members. This is also the case in abstract classes, especially if you don't want to give the inheriting class access to your privates. E.g.:

public abstract class AbstractClass {
    private int value;
    public AbstractClass (int value) {
        this.value = value;
    }
}

public class ConcreteClass extends AbstractClass {
    public ConcreteClass (int value) {
        super(value);
    }
}
Mureinik
  • 252,575
  • 45
  • 248
  • 283
1

Yes it is true that you can not initialize the objects of abstract class directly but this class can be super class from which some other class is extended and Parent class constructor is invoked when the child object is created.

Your question,

Then what is the purpose of constructor in an abstract class?

It is mainly useful to initialize parameters with some default value when an object is created of class which extends the abstract class that's what generally known as initialization section and if you do not place a constructor in abstract class then compiler itself creates a default constructor.

dbw
  • 5,842
  • 2
  • 21
  • 56
0

Abstract class can be parent of some class

Parent class constructor gets called even at the time of child object creation.

Rest brainstorming I leave it to you

dev2d
  • 3,991
  • 2
  • 26
  • 50
0

Basic concept of inheritance is first instantiate super class then sub class. So when we inherit an abstract class so JVM first instantiate to super class. So for instantiate the class constructor is useful.

Rahul Sahu
  • 254
  • 1
  • 4
  • 15