What use are constructors in abstract classes? [du

2019-02-25 08:00发布

问题:

This question already has an answer here:

  • Can an abstract class have a constructor? 21 answers

Since we can't instantiate an abstract class, then what is the necessity of having constructors in abstract class?

回答1:

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).



回答2:

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



回答3:

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...
}


回答4:

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