Woodstock Blog

a tech blog for general algorithmic interview questions

[Java OOP] Can Abstract Class Have Constructor

A short answer

In Java, all classes must have a constructor.

Can abstract class have constructor

Yes, it can. However, if we create an instance using it, it’s error.

Consider this example:

abstract class Base {
    Base() { System.out.println("Base Constructor Called"); }
    abstract void fun();
}

class Derived extends Base {
    Derived() { System.out.println("Derived Constructor Called"); }
    void fun() { System.out.println("Derived fun() called"); }
}

class Main {
    public static void main(String args[]) { 
       Derived d = new Derived();
    }
}

Output:

Base Constructor Called
Derived Constructor Called

More info on constructor:

The constructor in an abstract class:

  1. is used when you want to perform some initialization
  2. you may define more than one constructor (with different arguments)
  3. if you don’t define a constructor, then the compiler will automatically generate one for you.
  4. your subclass constructor have to call a constructor from the abstract class
  5. you can define all your constructors protected (cuz making them public is pointless)

For more on abstract class, read [Java OOP] Template method pattern.