“这个”怎么样? Java继承中的关键字工作? [英] How does the "this" keyword in Java inheritance work?

查看:73
本文介绍了“这个”怎么样? Java继承中的关键字工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码段中,结果确实令人困惑。

In the below code snippet, the result is really confusing.

public class TestInheritance {
    public static void main(String[] args) {
        new Son();
        /*
        Father father = new Son();
        System.out.println(father); //[1]I know the result is "I'm Son" here
        */
    }
}

class Father {
    public String x = "Father";

    @Override
    public String toString() {
       return "I'm Father";
    }

    public Father() {
        System.out.println(this);//[2]It is called in Father constructor
        System.out.println(this.x);
    }
}

class Son extends Father {
    public String x = "Son";

    @Override
    public String toString() {
        return "I'm Son";
    }
}

结果是

I'm Son
Father

为什么this指向父构造函数中的Son,但是this.x指向Father中的x字段。 this关键字是如何工作的?

Why is "this" pointing to Son in the Father constructor, but "this.x" is pointing to "x" field in Father. How is the "this" keyword working?

我知道多态概念,但[1]和[1]之间没有区别[2]?当新的Son()被触发时,内存中发生了什么?

I know about the polymorphic concept, but won't there be different between [1] and [2]? What's going on in memory when new Son() is triggered?

推荐答案

所有成员函数都是多态的默认情况下在Java中。这意味着当你调用this.toString()时,Java使用动态绑定来解析调用,调用子版本。当您访问成员x时,您访问当前作用域的成员(父亲),因为成员不是多态的。

All member functions are polymorphic in Java by default. That means when you call this.toString() Java uses dynamic binding to resolve the call, calling the child version. When you access the member x, you access the member of your current scope (the father) because members are not polymorphic.

这篇关于“这个”怎么样? Java继承中的关键字工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆