抽象类初始化 [英] Abstract Class Initialization

查看:156
本文介绍了抽象类初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个抽象类:

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

推荐答案


初始化仍然给我一个错误,但是为什么

initialization its still giving me an error but why

因为该类是抽象的。不管是否有抽象方法,抽象类都只能直接实例化 。从JLS 第8.1.1.1节

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:


如果尝试使用类实例创建表达式来创建抽象类的实例,则这是编译时错误(§ 15.9)。

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.

这篇关于抽象类初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆