【问题标题】:As an abstract class cannot be instantiated, why is a constructor still allowed inside the abstract class? [duplicate]既然抽象类不能被实例化,为什么抽象类内部还允许有构造函数呢? [复制]
【发布时间】:2017-12-08 16:06:42
【问题描述】:

什么是纯虚函数?什么是构造函数?

public abstract class AmAbstract
{
    private String name;
    public  AmAbstract(){
    }
    public  AmAbstract(String name){
    }
}

【问题讨论】:

  • 可以实例化为匿名类。无论如何你必须实现抽象方法

标签: java


【解决方案1】:

抽象类的具体子类的构造函数仍然必须调用其超类的构造函数,即使它是抽象的。

也就是说,抽象类构造函数没有理由拥有public 访问权限。 protected 访问就足够了。

public class Concrete extends AmAbstract
{
    public Concrete () {
        super (); // invoke the constructor of the abstract class
    }
    public Concrete (String name){
        super (name); // invoke the constructor of the abstract class
    }
}

【讨论】:

    猜你喜欢
    • 2020-11-15
    • 2018-09-10
    • 2013-05-05
    • 1970-01-01
    • 2013-11-25
    • 1970-01-01
    • 1970-01-01
    • 2020-04-29
    • 2013-08-23
    相关资源
    最近更新 更多