多态如何对内部类起作用? [英] How does polymorphism work for inner classes?
问题描述
当我试图了解如何在Java中使用集合时,我意识到我不了解多态如何为内部类工作.
When I tried to understand how to work with collections in java, I realised that I don't understand how polymorphism works for inner classes.
简单的代码示例:
class Parent {
public static void main(String[] args) {
new Parent().newInnerClass().myMethod();
new Child().newInnerClass().myMethod();
}
public I newInnerClass() {
return new InnerClass();
}
private final class InnerClass implements I {
@Override
public void myMethod() {
System.out.println("parent inner class");
foo();
}
}
public void foo() {
System.out.println("foo from parent");
}
}
class Child extends Parent {
public void foo() {
System.out.println("foo from child");
}
}
interface I {
void myMethod();
}
结果:
parent inner class
foo from parent
parent inner class
foo from child
因此,第一个链接会影响第三个方法的调用.我感到惊讶.
Therefore first link affects the third method invocation. It is surprising to me.
最初,我认为需要根据链接选择所需的方法.但是new Parent().newInnerClass()
和new Child().newInnerClass()
是从Parent
到InnerClass
的链接.
Initially I thought that needed methods selected accordind to the link. But new Parent().newInnerClass()
and new Child().newInnerClass()
are links to InnerClass
from Parent
.
你能澄清我的误会吗?
如果InnerClass
在Child中并且从Parent
扩展InnerClass
-这种行为对我来说就不足为奇了.
If InnerClass
was in Child and extended InnerClass
from Parent
- this behaviour wouldn't be surprising for me.
推荐答案
内部类中没有关于多态性的特殊规则.
There are no special rules for polymorphism in inner classes.
内部班级与普通班级有两点不同:
Inner class differs from regular class in two things:
- 内部类对其包含的对象持有隐式引用
- 内部类可以访问其包含类的
private
方法(此处不相关)
- Inner class holds an implicit reference to its containing object
- Inner class can access
private
methods of its containing class (not relevant here)
这是无需内部类即可重写示例的方式:
That's how you can rewrite your example without inner class:
class Parent {
...
public I newInnerClass() {
return new NotInnerClass(this);
}
...
}
class NotInnerClass implements I {
private final Parent containingObject;
public NotInnerClass(Parent containingObject) {
this.containingObject = containingObject;
}
@Override
public void myMethod() {
System.out.println("parent inner class");
containingObject.foo();
}
}
此代码产生与您相同的输出,因为在您调用时
This code produces the same output as your, because when you invoke
new Child().newInnerClass().myMethod();
containingObject
是Child
,containingObject.foo()
是常规的多态调用.
containingObject
is a Child
and containingObject.foo()
is a regular polymorphic call.
使用内部类时,编译器会在后台执行相同的操作.
When you use inner class, compiler does the same thing behind the scenes.
这篇关于多态如何对内部类起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!