跳至主要內容
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?

4563博客

全新的繁體中文 WordPress 網站
  • 首頁
  • (小白问题) Java 关于 this 的指向问题
未分類
14 10 月 2020

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

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

資深大佬 : rabbbit 1

这个 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)

  • 資深大佬 : yumenawei

    帮顶~

  • 資深大佬 : billlee

    字段没有多态性,this.name 取的是编译期 this 变量所属类的 name, 对于 Person::getName 来说,this 是 Person, this.name 是 “foo”.
    对于 main 中的 s.name 来说,s 是 Student, s.name 是 “bar”.

  • 資深大佬 : oneisall8955

    多态针对接口(行为,方法),属性没有多态

  • 資深大佬 : dushe

    this 指向最近的对象

文章導覽

上一篇文章
下一篇文章

AD

其他操作

  • 登入
  • 訂閱網站內容的資訊提供
  • 訂閱留言的資訊提供
  • WordPress.org 台灣繁體中文

51la

4563博客

全新的繁體中文 WordPress 網站
返回頂端
本站採用 WordPress 建置 | 佈景主題採用 GretaThemes 所設計的 Memory
4563博客
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?
在這裡新增小工具