多态三要素:
1.继承 2.重写父类方法 3.父类引用指向子类对象
代码:
package _20191211;
/**
* 多态
* @author TEDU
*
*/
public class PolymorphicTest {
/**
*多态三要素:
*1.继承
*2.重写父类方法
*3.父类引用指向子类对象
*/
public static void main(String[] args) {
Animal animal = new Animal();
animal.shout();//没有多态
Animal dog = new Dog();//3. 父类引用指向子类对象
dog.shout();//父类引用调用重写的方法,多态发生
//换个Cat试试
Animal cat = new Cat();
cat.shout();
}
}
class Animal{
public void shout() {
System.out.println("叫~");
}
}
class Dog extends Animal{//1.继承
@Override
public void shout() {// 2.重写父类方法
System.out.println("汪汪汪~");
}
}
class Cat extends Animal{
@Override
public void shout() {
System.out.println("喵喵喵~");
}
}
结果:
叫~ 汪汪汪~ 喵喵喵~
原文:https://www.cnblogs.com/Scorpicat/p/12022666.html