Java 面向對象 之 super 關鍵字

http://www.verejava.com/?id=17159596599630java

/**

    this: 表明當前類的引用
        1. 當局部變量和成員變量同名時,  成員變量要加 this 限定
        2. 實例化時 能夠用 this 調用當前類的構造方法,   必須寫在第一行
        3. 能夠用 this  調用當前類的 普通方法

    super : 表明當前父類的引用
        1. 實例化子類時,  能夠用  super 調用父類的 非私有方法
        2. 實例化子類時.    能夠用 super 調用父類的  構造方法 ,  必須寫在第一行
        3. 在子類的方法中 , 能夠用 supe 調用父類的 非私有方法.
*/
public class Test1 {

    public static void main(String[] args) {
        // 實例化 農夫

        Father father = new Father();
        father.setName("農夫");
        father.setAge(90);
        System.out.println(father.getAge() + " 歲 " + father.getName() + " 有 " + father.getWealth());

        Father father = new Father("農夫", 90);
        System.out.println(father.getAge() + " 歲 " + father.getName() + " 有 " + father.getWealth());

        Son son = new Son("農夫", 90);
        System.out.println("兒子知道父親的 : " + son.getAge() + " 歲 " + son.getName() + " 有 " + son.getWealth());
        son.work();
    }
}

//父類
class Father {
    
    private String name;
    private int age;
    private String wealth;

    public Father() {
        wealth = "100兩黃金";
    }
相關文章
相關標籤/搜索