1) Can Abstract Class Have Constructors in Java?
1) Can Abstract Class Have Constructors in Java?
Yes, an abstract class can declare and define a constructor in Java. Since you can not create an
instance of an abstract class, a constructor can only be called during constructor chaining, i.e.
5 when you create an instance of the concrete implementation class.
Now some interviewer, ask what is the purpose of a constructor, if you can not instantiate
abstract class? Well, it can still be used to initialize common variables, which are declared inside
an abstract class, and used by the various implementation.
Also even if you don’t provide any constructor, the compiler will add default no-argument
10 constructor in an abstract class, without that your subclass will not compile, since the first
statement in any constructor implicitly calls super(), default superclass constructor in Java.
Since AbstractList implements all common methods, concrete implementations like LinkedList
and ArrayList are free from the burden of implementing all methods, had they implemented List
20 interface directly.
It’s best of both worlds, you can get the advantage of interface for declaring type, and flexibility
of abstract class to implement common behavior in one place. Effective Java has a nice chapter
on how to use interface and abstract class in Java, which is worth reading.
Now, In order to implement this method, you need to extend abstract class and override this
method.