[代碼清單 1] java
class Father{ public int age; public void info(){ System.out.println("父類的方法"); } } public class Son extends Father{ public String name; }咱們知道子類Son如今應該已經擁有父類的age實例變量和info方法。可是這並非徹底擁有。
class Father{ public int count = 10; public void show(){ System.out.println(this.count); } } class Son extends Father{ public int count = 100; @override //重寫標誌 強制程序員重寫此方法不然編譯時錯誤 public void show(){ System.out.println(this.count); } } public class Test{ public static void main(String[] args){ Father f = new Father(); System.out.println("Father類型的Father對象f:" + f.count); A f.show(); Son s = new Son(); System.out.pritln("Son類型的Son對象s" + s.count); B s.show(); Father fs = new Son(); System.out.println("Father類型的Son對象fs" + fs.count); C fs.show(); Father f2s = s; System.out.println("Father類型的Son對象f2s" + f2s.count); D f2s.show(); } }看完上述代碼咱們來討論一下輸出結果。
class Father{ String str = "父類變量"; public Father getThis(){ return this; } public void info(){ System.out.println("父類方法"); } } public class Son{ String str = "子類變量"; @override public void info(){ System.out.println("子類方法"); } public void showFatherInfo(){ super.info(); } public Father getFather(){ return super.getThis(); } public static void main(String[] args){ Son s = new Son(); Father f = s.getFather(); System.out.println(s==f+","+s.str+","+f.str); s.info(); f.info(); s.showFatherInfo(); } }小夥伴們看到結果沒?s==f 會輸出ture,說明s和f指向同一個對象,那麼是哪一個對象呢?而後咱們看到s.str和f.str 分別輸出子類變量和父類變量。爲何?由於子類方法getFather()其實是返回了一個Father類型的Son對象。因此s.info(); 和f.info();輸出都是子類方法。s.showFarherInfo()才真正是父類的行爲方法。 最後,有幾點super的注意事項: 1.super不能夠直接用做引用變量,super == s;編譯時錯誤。 2.不能夠return super; 3.父類中的類變量能夠用super.str或者類名.str訪問。