為什么Java中類的成員變量不能被重寫?

這篇文章討論了Java面向?qū)ο蟾拍钪幸粋基本的概念--Field Hiding(成員變量隱藏)

成員變量在Java中能夠被重寫么?
Let’s first take a look at the following example which creates two Sub objects. One is
assigned to a Sub reference, the other is assigned to a Super reference.
我們看下面這個例子,我們創(chuàng)建了兩個子對象,一個使用的是子對象的引用,一個使用的是父對象的引用。

public class FieldOverriding {
 
    public static void main(String[] args) {
        Sub c1 = new Sub();
        Super c2 = new Sub();
        System.out.println(c1.s);
        System.out.println(c2.s);
 
    }
 
}
 
class Super {
    String s = "Super";
}
 
class Sub extends Super {
    String s = "Sub";
}
程序的輸出結(jié)果是:


Paste_Image.png
按照我們已有的多態(tài)的概念,第二個應該是輸出sub才對,但卻輸出了super。這是為什么呢?

不會重寫成員變量,而是隱藏成員變量
Java文檔中對隱藏域的定義:

Within a class, a field that has the same name as a field in the superclass hides the superclass’s field, even if their types are different. Within the subclass, the field in the superclass cannot be referenced by its simple name. Instead, the field must be accessed through super. Generally speaking, we don’t recommend hiding fields as it makes code difficult to read.

意思就是:

在一個類中,子類中的成員變量如果和父類中的成員變量同名,那么即使他們類型不一樣,只要名字一樣。父類中的成員變量都會被隱藏。在子類中,父類的成員變量不能被簡單的用引用來訪問。而是,必須從父類的引用獲得父類被隱藏的成員變量,一般來說,我們不推薦隱藏成員變量,因為這樣會使代碼變得難以閱讀。

其實,簡單來說,就是子類不會去重寫覆蓋父類的成員變量,所以成員變量的訪問不能像方法一樣使用多態(tài)去訪問。

訪問隱藏域的方法
就是使用父類的引用類型,那么就可以訪問到隱藏域,就像我們例子中的代碼

就是使用類型轉(zhuǎn)換System.out.println(((Super)c1).s);

北大青鳥網(wǎng)上報名
北大青鳥招生簡章