【问题标题】:Why "THIS" keyword denotes Child object into Parent class's method?为什么“THIS”关键字将子对象表示为父类的方法?
【发布时间】:2019-07-18 10:29:38
【问题描述】:

我正在通过继承使用子关系和父关系。我编写了一个代码,其中我在 Parent 类的方法中使用了 'THIS' 关键字,并且在我的 Child 类中覆盖了相同的方法。当我使用“Super”关键字从子类覆盖方法调用父类方法时,然后在父类方法中,“THIS”关键字表示子对象类,当我使用“THIS”关键字从父类方法调用方法时,它调用子类方法(此方法相同,也可在父子类中使用覆盖)。

    class Parent {

    void onResume() {
        println("Parent:OnResume" + this) // Here 'this' denotes Child class's Object

        this.show() // here Child class's method is invoked
        show()      // here Child class's method is invoked as well
    }

    void show() {
        println("Parent:Show")
    }

}

class Child extends Parent {

    override 
    void onResume() {
        super.onResume()
        println("Child:->OnResume" + this)
    }

    override 
    void show() {
        println("Child:Show")
    }

}

//Calling code
Parent parentRef = new Child()
parentRef.onResume()

如果我使用父类引用变量创建子类对象

Parent parentRef = new Child()

然后'this'表示Parent类的onResume()方法中的Child对象,当我们在Parent中调用show()方法时,它会调用Child类的show()方法。

请让我清楚为什么会这样。据我所知,“this”指的是类的当前对象,所以这里为什么“this”指的是来自父类的子对象。 为此,请提供深入的内部细节。提前致谢。

【问题讨论】:

标签: java inheritance this


【解决方案1】:

this 引用当前实例。如果创建Child的实例,则this的运行时类型为Child,不管是在父类代码还是子类代码中写this

如果你在Parent类代码中调用this.someMethod(),如果someMethodChild类覆盖,Child类方法将被执行。

【讨论】:

  • 请纠正我如果我错了,我知道当我们创建一个子类对象时,也会在内部创建父类对象,那么为什么“this”不表示父类对象为父类?或者请告诉我是否应用了其他概念?
  • @SaadBinIqbal 您使用new Child() 创建了一个Child 实例。此实例具有Child 类和Parent 类的属性,但其运行时类型为Child。因此this 的运行时类型始终为Child
  • @SaadBinIqbal 仅创建 1 个对象
【解决方案2】:

当你重写一个方法时,你重写了被重写方法的功能...... 除非子类从某个地方调用super.show()。换句话说,孩子完全控制原始(覆盖)功能是否仍然可用从哪里可用。 (子进程不仅可以从被覆盖的show() 中调用super.show(),还可以从其他方法和构造函数中调用它!)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-16
    • 2021-06-17
    • 2016-08-04
    • 1970-01-01
    • 1970-01-01
    • 2014-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多