[英]What happen when you call an override method using super and this keyword?
public class Superclass {
void method0(){
System.out.println("superclass");
}
}
public class Subclass extends Superclass{
void method0(){
System.out.println("subclass");
}
void method1(){
super.method0();
}
void method2(){
this.method0();
}
}
public class RunClass {
public static void main(String[] args){
new Subclass().method1();
new Subclass().method2();
}
}
the code above print out 上面的代码打印出来
superclass
superclass
while I expect it to print out 我希望它能打印出来
superclass
subclass
Isn't this.method0() refer to the method0 in subclass and print out subclass instead of superclass ? this.method0()不是引用子类中的method0并打印出子类而不是超类吗?
super
represents the instance of parent class. super
表示父类的实例。 this
represents the instance of current class. this
代表当前类的实例。 It will print 它将打印
superclass 超类
subclass 子类
I ran your code and it gaves me 我运行了您的代码,它给了我
superclass
subclass
this what should printed every thing seems ok 这个应该打印的东西似乎还可以
new Subclass().method1();
executes the method1()
of Subclass
instance, which in turn calls super.method0();
执行
Subclass
实例的method1()
,后者依次调用super.method0();
ie parent class instance's method0()
ie Superclass
instance method0()
. 即父类实例的
method0()
即Superclass
实例method0()
。
new Subclass().method2();
executes the method2()
of Subclass
instance, which in turn calls this.method0();
执行
Subclass
实例的method2()
,该实例又调用this.method0();
ie this instance's method0()
ie Subclass
instance method0()
. 即该实例的
method0()
即Subclass
实例method0()
。
super
is used to access instance members of the parent class while this
is used to access members of the current class. super
被使用,而访问父类的实例成员this
是用来访问当前类的成员。
First of all, it prints out the what you are expecting. 首先,它可以打印出您的期望。
Second, 第二,
Isn't this.method0() refer to the method0 in subclass and print out subclass instead of superclass?
this.method0()不是引用子类中的method0并打印出子类而不是超类吗?
this
=> refer to current object, using it you can use it (kinda of pointer to itself, in general terms ) this
=>引用当前对象,使用它就可以使用它(一般来说,指向自身的指针种类)
super
=> refer to super class object in an hierarchy, usually used to access the hidden members in subclass super
=>引用层次结构中的超类对象,通常用于访问子类中的隐藏成员
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.