gpt4 book ai didi

java - 抽象类的对象是匿名内部类吗?

转载 作者:行者123 更新时间:2023-12-04 04:48:37 27 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Can we instantiate an abstract class?

(16 个答案)


8年前关闭。




当我创建一个抽象类的对象时,我必须像接口(interface)一样这样做。

AbstractClass abstractClass = new AbstractClass() {

@Override
public void abstractMethod() {
}
};

这是否意味着 AbstractClass 的对象是匿名内部类对象吗?

最佳答案

AbstractClass abstractClass = new AbstractClass() {

@Override
public void abstractMethod() {
}
};

这段代码意味着您正在创建一个扩展 AbstractClass 的匿名类。 .您也可以对接口(interface)使用相同的符号。
SomeInterface someImplementingClass = new SomeInterface(){/*some code here*/};

这意味着您正在创建一个实现 SomeInterface 的类。 .

请注意,创建匿名类时有一定的限制。由于匿名类已经在扩展父类型,你不能让它扩展另一个类,因为在 java 中你只能在类上扩展。

此代码将有助于理解匿名类中覆盖方法的概念
class Anonymous {
public void someMethod(){
System.out.println("This is from Anonymous");
}
}

class TestAnonymous{
// this is the reference of superclass
Anonymous a = new Anonymous(){ // anonymous class definition starts here
public void someMethod(){
System.out.println("This is in the subclass of Anonymous");
}
public void anotherMethod(){
System.out.println("This is in the another method from subclass that is not in suprerclass");
}
}; // and class ends here
public static void main(String [] args){
TestAnonymous ta = new TestAnonymous();
ta.a.someMethod();
// ta.a.anotherMethod(); commented because this does not compile
// for the obvious reason that we are using the superclass reference and it
// cannot access the method in the subclass that is not in superclass
}

}

这输出
This is in the subclass of Anonymous

请记住 anotherMethod在作为匿名类创建的子类中实现。和 aAnonymous 类型的引用变量即匿名类的父类(super class)。所以声明 ta.a.anotherMethod();编译器错误为 anotherMethod()Anonymous 中不可用.

关于java - 抽象类的对象是匿名内部类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17787445/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com