1. 程式人生 > >多態 學習

多態 學習

n) SM out code fly 父類引用 sta ani father

dome1
class Demo1_Polymorphic {
    public static void main(String[] args) {
        Cat c = new Cat();
        c.eat();

        Animal a = new Cat();               //父類引用指向子類對象
        a.eat();
    }
}
/*
* A:多態(polymorphic)概述
    * 事物存在的多種形態 
* B:多態前提
    * a:要有繼承關系。
    * b:要有方法重寫。
    * c:要有父類引用指向子類對象。
* C:案例演示
    * 代碼體現多態
*/
class Animal {
    public void eat() {
        System.out.println("動物吃飯");
    }
}

class Cat extends Animal {
    public void eat() {
        System.out.println("貓吃魚");
    }
}

dome2

class Demo2_Polymorphic {
    public static void main(String[] args) {
        /*Father f = new Son();                 //父類引用指向子類對象
        System.out.println(f.num);

        Son s = new Son();
        System.out.println(s.num);*/

        Father f = new Son();
        //f.print();
        f.method();                         //相當於是Father.method()
    }
}
/*
成員變量
編譯看左邊(父類),運行看左邊(父類)
成員方法
編譯看左邊(父類),運行看右邊(子類)。動態綁定
靜態方法
編譯看左邊(父類),運行看左邊(父類)。
(靜態和類相關,算不上重寫,所以,訪問還是左邊的)
只有非靜態的成員方法,編譯看左邊,運行看右邊 
*/
class Father {
    int num = 10;
    public void print() {
        System.out.println("father");
    }

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

class Son extends Father {
    int num = 20;

    public void print() {
        System.out.println("son");
    }

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

dome3

class Demo3_SuperMan {
    public static void main(String[] args) {
        Person p = new SuperMan();          //父類引用指向子類對象,超人提升為了人
                                            //父類引用指向子類對象就是向上轉型
        System.out.println(p.name);
        p.談生意();
        SuperMan sm = (SuperMan)p;          //向下轉型
        sm.fly();

        /*
        基本數據類型自動類型提升和強制類型轉換
        */
        int i = 10;
        byte b = 20;
        //i = b;                        //自動類型提升
        //b = (byte)i;                  //強制類型轉換
    }
}

class Person {
    String name = "John";
    public void 談生意() {
        System.out.println("談生意");
    }
}

class SuperMan extends Person {
    String name = "superMan";

    public void 談生意() {
        System.out.println("談幾個億的大單子");
    }

    public void fly() {
        System.out.println("飛出去救人");
    }
}

多態 學習