/**
* @Lin 2018.5.7
* Animal a = new Dog()
* 父类的引用指向子类的对象,此为多态性Polymorphism。
* 此对象a能调用父类的方法和子类重写的方法,父类被重写的方法被覆盖了。
* !! 不能调用子类添加的方法, 除非强制转化为子类的对象 ((Dog).a).play()
* Animal a = new Dog(); //a是父类Animal的对象,所以默认可以调用父类的所以方法(重写的会被子类覆盖),它不能调用子类的新加方法,但是是指向子类,可以调用子类的重写方法
* 构造方法从父类到子类。
*/
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(); // 构造方法先运行父类,再到子类
d.go();
d.eat();
System.out.println("------");
System.out.println("父类的引用指向子类的对象");
Animal a = new Dog();
a.eat(); // 子类重写父类的方法
((Dog)a).play(); // 强制转化可以调用子类新添加的方法
a.go(); // 父类的方法
}
}
输出:
Animal 构造方法!!
Dog 构造方法!!
Animal go 父类没被子类重写的方法
Dog eat 子类重写父类的方法
------
父类的引用指向子类的对象
Animal 构造方法!!
Dog 构造方法!!
Dog eat 子类重写父类的方法
Dog play -- 子类添加的方法
Animal go 父类没被子类重写的方法
Process finished with exit code 0