[英]How can we call methods overridden in a java anonymous class?
Consider the code below : 考虑下面的代码:
abstract class AbstractClass {
abstract m1();
}
public class Test {
public static void main(String [] args) {
AbstractClass obj = new AbstractClass() {
@Override void m1() {
System.out.print("Instance of abstract class !");
}
};
obj.m1();
}
}
Now here is what I did not understand about this code. 现在这是我对这段代码不了解的内容。
I read that anonymous class creates the class with unknown name which extends the class whose reference is provided (here it is abstract AbstractClass). 我读到匿名类创建了一个名称未知的类,该类扩展了提供其引用的类(这里是抽象AbstractClass)。
Also I remember that we cannot implement the method of child class if the the object is having reference of parent class. 我还记得如果对象具有父类的引用,则无法实现子类的方法。
see block of code below 请参阅下面的代码块
Parent obj = new Child();
obj.methodOfParent();
obj.methodOfChild(); //this gives error
Now here is my point if Anonymous Class extends its Parent Class whose reference is provided, then how can we call overriden methods of Parent Class from Anonymous Class? 现在我要说的是,如果匿名类扩展了其父类 (提供了其引用),那么我们如何从匿名类中调用父类的重写方法呢?
There is a difference between calling an overridden method of parent and calling a method of child. 调用父级的重写方法和调用子级方法之间是有区别的。 If a method is declared in class T
, you can call it on a variable statically typed as T
, regardless of where the method is actually implemented. 如果方法在类T
声明,则可以在静态类型为T
的变量上调用该方法,而不管该方法实际在何处实现。
In your example, if obj.methodOfParent()
happens to be a method override from Child
, the method in Child
will run, even though obj
's static type is Parent
. 在你的榜样,如果obj.methodOfParent()
恰好是从方法重写Child
,在该方法中Child
将运行,即使obj
的静态类型是Parent
。
Same mechanism is in play with anonymous classes: the reason that you are allowed to call obj.m1()
is that m1()
has been declared in the parent class. 匿名类具有相同的机制:允许调用obj.m1()
是m1()
已在父类中声明。
I guess you just miss one point. 我想你只想念一分。 Let me show you example: 让我举个例子:
class Parent {
public void methodOfParent() {}
public void methodOfParentToBeOverriden() {}
}
class Child extends Parent {
@Override public void methodOfParentToBeOverriden() {}
public void methodOfChild() {}
}
Parent obj = new Child();
obj.methodOfParent(); //this is OK
obj.methodOfParentToBeOverriden(); // this is OK too
obj.methodOfChild(); //this gives error
((Child)obj).methodOfChild(); //this is OK too here.
Please note that when you call obj.methodOfParentToBeOverriden()
it will be called implementation from Child class. 请注意,当您调用obj.methodOfParentToBeOverriden()
,它将被称为Child类的实现。 Independence did you cast this object to Parent type or not. 您是否将此对象强制转换为Parent类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.