Can we define a parameterized constructor in an abstract class in Java?

JavaObject Oriented ProgrammingProgramming

Yes, we can define a parameterized constructor in an abstract class.

Conditions for defining a parameterized constructor in an abstract class

  • We need to make sure that the class which is extending an abstract class have a constructor and it can call the superclass parameterized constructor.
  • We can call the superclass parameterized constructor in a subclass by using super() call.
  • If we are not placing super() call in the subclass constructor, a compile-time error will occur.

Example

Live Demo

abstract class AbstractClassTest {
   AbstractClassTest(int a) { // Parameterized Constructor
      System.out.println("Parameterized Constructor of an abstract class a="+ x);
   }
}
public class Test extends AbstractDemo {
   Test() {
      super(20);
      System.out.println("Test Class Constructor");
   }
   public static void main(String[] args) {
      Test obj = new Test();
   }
}

In the above example, we must place a super() call in the subclass constructor (Test), if not a compile-time error will occur.

Output

Parameterized Constructor of an abstract class a=20
Test Class Constructor
raja
Published on 04-Jul-2019 15:32:11
Advertisements