简体   繁体   English

使用“this”调用超类方法的子类

[英]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.为了更好地理解,我创建了几个示例类。

Parent Class父 Class

public class TestClass{
    public void func(){
        this.cFunc();
        System.out.println("In Parent");
    }

    public void cFunc(){
        System.out.println("cFunc in parent");
    }
}

Child Class儿童 Class

public class TestClassChild extends TestClass{
    public void cFunc(){
        System.out.println("cFunc in child");
    }
}

Cases案例

1) Child Object accessed using Child Class reference 1) 子 Object 使用子 Class 参考访问

TestClassChild tc = new TestClassChild();
tc.func();
Output Output
TestClass t = new TestClassChild();
t.func();

2) Child Object accessed using Parent Class reference 2) 子 Object 使用父 Class 参考访问

TestClass t = new TestClassChild(); t.func();
Output Output
 cFunc in child - Irrespective if it was referenced by parent still child method got called. In Parent

3) Parent Object accessed using Parent Class reference 3) 使用父 Class 参考访问的父 Object

 TestClass tp = new TestClass(); tp.func();
Output 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM