多态-“花木兰替父从军”

HuaFu.java

public class HuaHu {
    public String name = "花父";
    public  int age = 46;
    public static void sayMe(){
        System.out.println("大家好,我是花父,今年46岁");
    }
    public void fight(){
        System.out.println("打架");
    }
}

HuaMuLan.java

public class HuaMuLan extends HuaHu {
    public String name = "花木兰";
    public int age = 19;
    public void dressing(){
        System.out.println("化妆");
    }
    public static void sayMe(){
        System.out.println("大家好,我是花木兰,今年19岁");
    }
}

ApplicationStory.java

public class ApplicationStory {
    private static Object HuaHu;

    public static void main(String[] args) {
        //花木兰替父从军-向上转型
        HuaHu huaHu = new HuaMuLan();
        System.out.println("" + huaHu.name);
        System.out.println("" + huaHu.age);
        huaHu.fight();
        huaHu.sayMe();
        //花木兰从新活回自己-向下转型
        HuaMuLan huaMuLan = (HuaMuLan) HuaHu;
        huaMuLan.dressing();
        huaMuLan.sayMe();

    }
}

你可能感兴趣的:(java,servlet,jvm)