Abstract Class Initialization

耗尽温柔 提交于 2019-12-04 02:50:39

问题


I have an abstract class:

abstract class Shape {

    public String color;
    public Shape() {
    }
     public void setColor(String c) {
        color = c;
    }
    public String getColor() {
        return color;
    }

    public double area() {
        return 0;
    }
}

Which provides non abstract methods and then i want to initialize it like:

     Shape object = new Shape();

so on initialization, it's still giving me an error, but why? If I provide one abstract method in the class, then it could be understandable that the class cannot be initialized. In this situation, why is it still giving an error? Any help would be appreciated


回答1:


initialization its still giving me an error but why

Because the class is abstract. An abstract class simply can't be instantiated directly, whether or not it's got abstract methods. From the JLS section 8.1.1.1:

It is a compile-time error if an attempt is made to create an instance of an abstract class using a class instance creation expression (§15.9).

If you haven't got any abstract methods and you want to be able to instantiate the class directly, make the class non-abstract. The only reason to make a class with no abstract methods abstract is to force the use of concrete subclasses.




回答2:


No, you can never instantiate an abstract class



来源:https://stackoverflow.com/questions/15803375/abstract-class-initialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!