Java 中的匿名 class 是否可以使用他的 superclass 之外的其他方法?

Can an anonymous class in Java have other methods than his superclass?

我知道匿名 classes 很适合覆盖等等,但我想知道您是否还可以添加 parent class 中不存在的其他方法,例如在下面的示例中。

这是我的 class,wieBenIk 是唯一的方法。

public class Driehoek {

//methoden
public void wieBenIk(){
    System.out.println("ik ben een driehoek");
}

}

这是我添加 newMethod 的匿名 class。

public class 主 {

public static void main(String[] args) {

    Driehoek test = new Driehoek(){

        @Override
        public void wieBenIk() {
            System.out.println("overrided by anonymous class");
        }

        public void newMethod(){
            System.out.println("I am a new method");
        }
    };

    test.newMethod();

}

}

我的问题是为什么 test.newMethod() 不起作用?是不是像另一个child class? 谢谢大家帮助我。

test 被声明为 Driehoek 的实例。因此,对于编译器,它将具有 Driehoek.

的成员

同样,如果你定义

Object test = new Driehoek() {....};

对于编译器 test 将只有 Object 成员可用。

如果您向匿名 class 添加更多成员,编译器将不知道 test 有那些可用的方法。所以它不允许你使用它们