我正在开始 Java 编程,并且遇到了抽象类。我知道如果不创建将它们扩展为子类的具体类,就无法实例化它们。然而,当我尝试这段代码并且它运行正常时,我真的很困惑。
abstract class Communication{
public void FirstMethod()
{
System.out.println("I am first method()\n");
}
}
public class Main{
public static void main(String[] args){
Communication communication = new Communication() {
@Override
public void FirstMethod(){
super.FirstMethod();
}
};
communication.FisrtMethod();
}
}
输出是:我是第一个方法()。 如果我将其修改为:
Communication communication = new Communication() {
@Override
public void FirstMethod(){
System.out.println("I've been called from Main");
}
};
输出是:我被从 Main 调用。 有人可以解释一下这是否是一种实例化或者这是什么概念?
最佳答案
这被称为
Anonymous Class
定义: 没有类名声明的内部类称为匿名内部类。
对于匿名内部类,我们同时声明和实例化它们。一般来说,当您需要重写类或接口(interface)的方法时,就会使用它们。
关于java - 抽象类 'instantiation' 及其方法体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42668797/