rabbbit
V2EX  ›  问与答

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

  •  
  •   rabbbit · Oct 12, 2020 · 2396 views
    This topic created in 2218 days ago, the information mentioned may be changed or developed.

    这个 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
        }
    }
    
    
    4 replies  •  2020-10-13 14:02:03 +08:00
    yumenawei
    yumenawei
    Oct 12, 2020❤️1
    1
    帮顶~
    billlee
    billlee
    Oct 12, 2020❤️1
    2
    字段没有多态性,this.name 取的是编译期 this 变量所属类的 name, 对于 Person::getName 来说,this 是 Person, this.name 是 "foo".
    对于 main 中的 s.name 来说,s 是 Student, s.name 是 "bar".
    itechify
    itechify
    Oct 12, 2020 via Android❤️1
    3
    多态针对接口(行为,方法),属性没有多态
    dushe
    dushe
    Oct 13, 2020
    4
    this 指向最近的对象
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1369 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 15:31 · PVG 23:31 · LAX 07:31 · JFK 10:31
    ♥ Do have faith in what you're doing.