views:

91

answers:

4

We cant instantiate an abstract class.Then what is the necessity of having constructors in abstract class.Please give me some examples?

+3  A: 

Abstract classes are designed to be extended, each constructor from the child must perform a call to a constructor from the base class, thus you need constructors in your abstract class.

The abstract class is a skeleton and thus makes no sense to instantiate it directly since it is still incomplete (children will provide the rest).

dpb
+1  A: 

An example:

public abstract class BaseClass
{
    private String member;

    public BaseClass(String member)
    {
        this.member = member;
    }

    ... abstract methods...
}

public class ImplementingClass extends BaseClass
{
    public ImplementingClass(String member)
    {
        /* Implementing class must call a constructor from the abstract class */
        super(member);
    }

    ... method implementations...
}
izb
+1  A: 

We can use a abstract class constructor to execute code that is relevant for every subclass. This way preventing duplicate code

Bas
+1  A: 

Abstract classes can have fields and non-abstract methods(what makes it an abstract class rater than an interface). The fields probably need to be initialized when a class that extends it is instantiated.

Having a constructor in the abstract class allows you to call super(foo); to initialize them as opposed to doing it directly

CheesePls