Java多态性--父类的引用指向子类的对象

/**
 * @Lin 2018.5.7
 * Animal a = new Dog()
 * 父类的引用指向子类的对象,此为多态性Polymorphism。
 * 此对象a能调用父类的方法和子类重写的方法,父类被重写的方法被覆盖了。
 * !! 不能调用子类添加的方法。
 * 构造方法从父类到子类。
 */
class Animal {
    void eat() {
        System.out.println("Animal eat!");
    }

    public Animal() {
        System.out.println("Animal!!");
    }

    void go() {
        System.out.println("Animal go");
    }
}

class Dog extends Animal{
    public Dog() {
        System.out.println("Dog!!");
    }

    @Override
    void eat() {
        System.out.println("Dog eat");
    }

    void play() {
        System.out.println("Dog play");
    }
}

public class PolymorphismTest {
    public static void main(String[] args) {
        Dog d = new Dog();
        System.out.println("------");
        Animal a = new Dog();
        a.eat();
    }
}
输出:

猜你喜欢

转载自blog.csdn.net/chenbetter1996/article/details/80231927