rabbbit
V2EX  ›  问与答

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

  •  
  •   rabbbit · Oct 12, 2020 · 2048 views
    This topic created in 2052 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
        1
    yumenawei  
       Oct 12, 2020   ❤️ 1
    帮顶~
    billlee
        2
    billlee  
       Oct 12, 2020   ❤️ 1
    字段没有多态性,this.name 取的是编译期 this 变量所属类的 name, 对于 Person::getName 来说,this 是 Person, this.name 是 "foo".
    对于 main 中的 s.name 来说,s 是 Student, s.name 是 "bar".
    itechify
        3
    itechify  
    PRO
       Oct 12, 2020 via Android   ❤️ 1
    多态针对接口(行为,方法),属性没有多态
    dushe
        4
    dushe  
       Oct 13, 2020
    this 指向最近的对象
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   908 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 20:52 · PVG 04:52 · LAX 13:52 · JFK 16:52
    ♥ Do have faith in what you're doing.