多态 学习

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("飞出去救人");
    }
}

猜你喜欢

转载自blog.51cto.com/357712148/2131934