java 多态 深入理解多态

多态

package Lesson01;

public class Demo001 {

    public static void main(String[] args) {
        /*
         * 超人案例(深入理解多态-隐藏-低调-伪装)
         * 
         * 超人去美国找某某集团的老总谈生意 超人在别人面前,如果不说自己是超人,在别人面前表现的就是普通人 老总以为是谈小生意的,但实际是谈大生意
         * 老总以为他不会飞,实际上他会飞去救人
         */

        // 父类指向子类对象(多态)
        Person p = new SupperMan();
        p.fly();
        SupperMan sm = new SupperMan();
        sm.fly();
        
        SpiderMan sp1 = new SpiderMan();
        sp1.fly();
//        Person p1 = new Person();
//        SupperMan sm2 = (SupperMan) p1;
//        sm2.fly();
        
        
        test1(sm);
        test2(sp1);
        test(sm);
        test(sp1);
    }
    public static void test(Person per)
    {
        per.fly();
    }
    
    public static void test1(SupperMan sm) {
        sm.fly();
    }

    public static void test2(SpiderMan sm) {
        sm.fly();
    }

}


    // 普通人
    class Person {
        public void walk() {
            System.out.println("走....");
        }

        public void fly() {
            System.out.println("我是普通人,不会飞...");
        }
    }

    // 超人
    class SupperMan extends Person {
        public void fly() {
            System.out.println("超人飞去救人...");
        }
    }

        // 蜘蛛
    class SpiderMan extends Person{
        public void fly(){
            System.out.println("蜘蛛侠爬去救人...");
        }
    }

评论

h
hw_7864

⭐️ Admin快速开发: https://show.cool-admin.com/

赞 0
h
hw_7864

⭐️ 官方文档: https://cool-js.com

赞 0
h
hw_7864

⭐️ chatgpt在线体验: https://cool-js.com/ai/chat-vip/index.html?r=helloworld

赞 0