Java多態之Father f=new Son();


成員變量靜態方法看左邊,非靜態方法編譯看左邊,運行看右邊。

  • 左邊Father f其實是定義了一個Father類的對象,而右邊new Son()可以只理解為是一個重寫了Father類方法的對象。
  • 因此,f的成員變量,靜態方法都是Father類的,而只有被重寫的方法才是調用Son類的。
  • 所以編譯看左邊指的是如果調用Son類的特有方法的話會編譯錯誤,因為這個被重寫的Father類里並沒有這個Son類的特有方法。
class Father{
    int a=1;
    static int b=2;
    void say(){
        System.out.println("I am father");
    }

    void ffun(){
        System.out.println("father's function");
    }

    static void fun(){
        System.out.println("static father");
    }
}

class Son extends Father{
    int a=3;
    static int b=4;
    void say(){
        System.out.println("I am son");
    }

    void sfun(){
        System.out.println("son's function");
    }

    static void fun(){
        System.out.println("static son");
    }
}

public class Polymorphism1 {
    public static void main(String[] args) {
        Father a=new Son();
        a.say();
        a.ffun();
        System.out.println(a.a);
        Father b=new Father();
        b.say();
        b.ffun();
        System.out.println(b.a);
        Son c=new Son();
        c.say();
        c.sfun();
        System.out.println(c.a);
        System.out.println(Father.b);
        System.out.println(Son.b);
        Father.fun();
        Son.fun();
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM