抽象类和匿名类
abstract class Two {
Two() {
System.out.println("Two()");
}
Two(String s) {
System.out.println("Two(String");
}
abstract int display();
}
class One {
public Two two(String s) {
return new Two() {
public int display() {
System.out.println("display()");
return 1;
}
};
}
}
class Ajay {
public static void main(String ...strings ){
One one=new One();
Two two=one.two("ajay");
System.out.println(two.display());
}
}
我们无法实例化抽象类,那么为什么函数 Two Two(String s) 能够创建抽象类 Two 的实例???
abstract class Two {
Two() {
System.out.println("Two()");
}
Two(String s) {
System.out.println("Two(String");
}
abstract int display();
}
class One {
public Two two(String s) {
return new Two() {
public int display() {
System.out.println("display()");
return 1;
}
};
}
}
class Ajay {
public static void main(String ...strings ){
One one=new One();
Two two=one.two("ajay");
System.out.println(two.display());
}
}
we cannot instantiate an abstract class then why is the function Two two(String s) able to create an instance of abstract class Two ????
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它不会创建抽象
Two
的实例。它创建一个具体的匿名类,该类扩展Two
并实例化它。它几乎相当于使用这样的命名内部类:
It does not create an instance of abstract
Two
. It creates a concrete, anonymous class that extendsTwo
and instantiates it.It's almost equivalent to using a named inner class like this:
因为它实现了缺少的函数display()。它返回 Two 的匿名子类。如果您查看编译的文件,您可以看到这一点。您将在那里有一个 One$1.class,它扩展了 Two.class!
Because it implements the missing function display(). It returns an anonymous subclass of Two. You can see this if you look at the compiled files. You will have a One$1.class there, which extends Two.class!