多态性:
对象在运行过程中的多种形态。
方法的重载与重写。
对象的多态性。
用父类的引用指向子类对象(用大的类型去接受小的类型,向上转型、自动转换)
package no2;
public class Test5 {
public static void main(String[] args) {
Chicken hc = new HomeChicken ("Little chicken");
//hc.eat();
Chicken yc = new YeChicken("Big chicken");
//yc.eat();
//hc = yc;
//hc.eat();
eat(hc);
eat(yc);
}
//抽象
public static void eat(Chicken c) {
System.out.println("鸡儿吃饭");
c.eat();
}
}
//鸡
abstract class Chicken{
private String name;
public Chicken() {}
public Chicken(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public abstract void eat();
}
//家鸡
class HomeChicken extends Chicken{
public HomeChicken(String name) {
super(name);
}
public void eat() {
System.out.println(this.getName()+"like eating rice!");
}
}
//野鸡
class YeChicken extends Chicken{
public YeChicken(String name) {
super(name);
}
public void eat() {
System.out.println(this.getName()+"like eating worm!");
}
}