(小白问题) Java 关于 this 的指向问题

2020-10-12 21:16:03 +08:00
 rabbbit

这个 this 到底指向谁, 为什么 s.getName() 输出 foo, 而 s.name 输出 bar.
我以为两个都结果都应该是 bar,是哪里搞错了?

class Person {
    public String name = "foo";
    public String getName() {
        return this.name;
    }
}

class Student extends Person {
    public String name = "bar";
}

public class Hello {
    public static void main(String[] args) {
        Student s = new Student();
        System.out.println(s.getName()); // foo 
        System.out.println(s.name); // bar
    }
}

1257 次点击
所在节点    问与答
4 条回复
yumenawei
2020-10-12 21:49:57 +08:00
帮顶~
billlee
2020-10-12 21:54:16 +08:00
字段没有多态性,this.name 取的是编译期 this 变量所属类的 name, 对于 Person::getName 来说,this 是 Person, this.name 是 "foo".
对于 main 中的 s.name 来说,s 是 Student, s.name 是 "bar".
oneisall8955
2020-10-12 23:32:21 +08:00
多态针对接口(行为,方法),属性没有多态
dushe
2020-10-13 14:02:03 +08:00
this 指向最近的对象

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/714302

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX