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:
- is used when you want to perform some initialization
- you may define more than one constructor (with different arguments)
- if you don’t define a constructor, then the compiler will automatically generate one for you.
- your subclass constructor have to call a constructor from the abstract class
- you can define all your constructors protected (cuz making them public is pointless)
For more on abstract class, read [Java OOP] Template method pattern.