[英]Subclass calling a superclass method using “this”
If superclass has a method that uses the keyword " this
" and subclass call this method, would superclass method using " this
" refer to the subclass object?如果超类有一个使用关键字“
this
”的方法,而子类调用这个方法,那么使用“ this
”的超类方法是否会引用子类object?
No, this
will always referes to the instance of the class in which we are using it.不,
this
总是指我们使用它的 class 的实例。
If we use
this
in parent class it will always return parent class instance.如果我们在父 class 中使用
this
,它将始终返回父 class 实例。
If you want to use this
of child class in parent class method,Please override the method of parent class.如果您想在父 class 方法中使用子 class 的
this
,请覆盖父 class 的方法。
this
always refer to the self object. this
总是指自我 object。 ie., If a child uses this
reference, it points to child.即,如果一个孩子使用
this
引用,它指向孩子。 If a parent uses this
, it points to parent.如果父级使用
this
,它指向父级。
If this
cannot find a reference to what is needed in the self, then it looks for the reference in parent.如果
this
无法找到对自身所需内容的引用,则它会在父级中查找引用。
I doubt your confusion is coming from method overriding, where a parent may call a method with this
, but method in child is executed.我怀疑您的困惑来自方法覆盖,其中父母可能会使用
this
调用方法,但执行子方法中的方法。 This is because, the object which gets created in always of the child.这是因为,object 总是在子节点中创建。 So
this
points to child in that case.因此,在这种情况下,
this
指向孩子。
Put it simply, this
points to the instance of class which was instantiated.简单地说,
this
指向了实例化的 class 的实例。 If that instance does not contain the referred entity, then lookup is done on parent (if any)如果该实例不包含引用的实体,则在父级(如果有)上进行查找
The keyword this
in a class will always refer to the object. class 中的关键字
this
将始终指代 object。
I have crated few sample classes for better understanding.为了更好地理解,我创建了几个示例类。
public class TestClass{
public void func(){
this.cFunc();
System.out.println("In Parent");
}
public void cFunc(){
System.out.println("cFunc in parent");
}
}
public class TestClassChild extends TestClass{
public void cFunc(){
System.out.println("cFunc in child");
}
}
TestClassChild tc = new TestClassChild();
tc.func();
Output
TestClass t = new TestClassChild();
t.func();
TestClass t = new TestClassChild(); t.func();
Output
cFunc in child - Irrespective if it was referenced by parent still child method got called. In Parent
TestClass tp = new TestClass(); tp.func();
Output
cFunc in parent - Parent function got called. In Parent
Hope the below examples will make things clear for you.希望下面的例子能让你清楚。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.