01 多态初识

1. 举例

公司找父亲去帮忙开汽车, 父亲不在, 儿子伪装成父亲,结果儿子只能会开电瓶车,也就是说最终指向儿子类的开车方法->开电瓶车

代码如下

public class Dad {
    public void kaiche() {
        System.out.println("开汽车");
    }
}

public class Son extends Dad{
    public void kaiche() {
        System.out.println("开电频车");
    }
}

public class Test {
    public static void main(String[] args) {
        Dad j8 = new Son();
        j8.kaiche();
    }
}

2.1 正常类的多态

public class Fu {
    public void function() {
        System.out.println("我是爸爸");
    }
}

public class Zi extends Fu{
    @override
    public void function() {
        System.out.println("我是儿子");
    }
}

public class Test {

    public static void main(String[] args) {
        Fu fu = new Zi(); //左父右子 左接口右实现
        fu.function();//指向子类方法
    }

}
=============================================
>>>我是儿子

2.2 抽象类的多态

public abstract class Person {
    public abstract void run();
}

public class Theft extends Person{
    @Override
    public void run() {
        System.out.println("小偷在跑!");
    }
}

public class Test {

    public static void main(String[] args) {
        Person person=new Theft();
        person.run();//
    }
}
===========================================
>>>小偷在跑!

2.3 接口的多态

public interface Swimming {
    public abstract void swimming();
}

public class Child implements Swimming{
    @override
    public void swimming() {
        System.out.println("小孩在游泳");
    }
}

public class Test {

    public static void main(String[] args) {
        Swimming s=new Child();
        s.swimming()
    }

}
=====================================
>>>小孩在游泳

你可能感兴趣的:(01 多态初识)