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

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

问题描述

我有一个抽象类:

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天全站免登陆