【发布时间】:2017-03-14 21:58:51
【问题描述】:
超级关键字相关的疑问。
class Parent{
int x=40;
void show()
{
System.out.println("Parent");
}
}
class Child extends Parent
{ int x=20;
void show() //method overriding has been done
{
System.out.println(super.x); // prints parent data member
System.out.println(((Parent)this).x); /*same output as previous statement which means super is similar to (Parent)this*/
System.out.println("child");
super.show(); // invokes parent show() method
((Parent)this).show(); //Doesnt invoke parent show() method.Why?
}
public static void main(String s[])
{
Child c1=new Child(); //Child class object
c1.show();
}}
所以,System.out.println(super.x) 和 System.out.println(((Parent)this).x) 打印相同的值。所以如果 super.show() 调用父类 show() 方法,那么为什么 ((Parent)this).show(); 无法调用父类 show()?请对此作出适当的解释。
【问题讨论】:
-
您可能应该修复代码的缩进,然后有人会回答您的问题。
-
如果你可以调用方法(因为它是在父类中定义的),那么将
this指针转换为超类有什么意义,所以你可以只使用this.show();,@987654330 @ 或只是show()!?除非您在子类中覆盖了show方法,否则 super.show() 会调用父类而不是本地类。 -
((Base)this).show(); //Doesnt invokes parent show() method.Why?.. 什么是Base?应该是((Parent)this).show() -
你在
Child.show()中调用((Parent) this).show();(我认为这是你想要的)仍然会命中Child.show(),所以这是一个递归调用(导致无限递归)。我认为这回答了你的问题。 -
"不调用父 show() 方法。为什么?"出于同样的原因,调用这个:
Integer integer = Integer.valueOf(0); System.out.println(((Object) integer).toString());不会调用Object.toString()。
标签: java