繁体   English   中英

无法实例化匿名 class

[英]Cannot instantiate an anonymous class

我在这段简单的代码中遇到 2 个错误:

public class Test {
    public static void main(String args[]) {
        O o = new O() {

        };
    }
}

错误:

    Test.java:3: cannot find symbol
    symbol  : class O
    location: class Test                                  
    O o = new O() {                               
    ^
    Test.java:3: cannot find symbol                       
    symbol  : class O                                     
    location: class Test                                  
    O o = new O() {                               
                      ^                                   

这里有什么问题?

使用匿名内部类,您应该扩展现有的 class(并使用多态性覆盖方法)或现有接口。

使用此规则,代码将失败,因为没有现有的 class(类型)O。

尝试定义 class 并使用多态性覆盖父 class 中所需的方法。

正如评论所说,您必须在某处定义 class 。 此代码应该可以工作:

class O {}
public class Test {
    public static void main(String args[]) {
        O o = new O() {

        };
    }
}

尝试:

public class Test {
    public static void main(String args[]) {
        Test  o = new Test () {

        };
        System.out.println(o.getClass().getName());
    }
}

你会得到Test$1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM