package QianFeng02;
//多态
public class Polymorphic {
public static void main(String[] args){
// HomeCh homeCh=new HomeCh("家鸡1");//一般实例化
Chickens homeCh=new HomeCh("家鸡1");//Chickens是父类 HomeCh是子类(多态)
homeCh.eat();
Chickens pheasant=new Pheasant("野鸡2");
pheasant.eat();
//用父类的引用指向子类的对象
// homeCh=pheasant;
// homeCh.eat();
System.out.println("------------------------");
eat(homeCh);
eat(pheasant);
Chickens jan=new Jan("尖叫鸡4");//Chickens也可以替换为Jan
eat(jan);
}
//抽象:::面向抽象编程
public static void eat(Chickens c){//Chickens是父类可以传不同类的对象(而不是只传jan对象或者homeChdu对象)
System.out.println("鸡翅3");
c.eat();
}
}
//鸡
// 不能被实例化
//抽象类的非抽象子类必须对父类抽象方法进行覆盖
abstract class Chickens{//父类一般定义为抽象类
private String name;
public Chickens(){}
public Chickens(String name){
this.name=name;
}
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public abstract void eat();//抽象方法必须定义为public或者abstract
}
//家鸡
class HomeCh extends Chickens{
public HomeCh(String name){
super(name);//调用父类带参数构造方法(因为父类带参构造)
}
@Override
public void eat() {
System.out.println(getName()+"吃大米");
}
}
//野鸡
class Pheasant extends Chickens{
public Pheasant(String name){
super(name);
}
@Override//重写抽象类父类的方法
public void eat() {
System.out.println(getName()+"吃虫子");
}
}
//尖叫鸡
class Jan extends Chickens{
public Jan(String name){
super(name);
}
@Override//重写抽象类父类的方法
public void eat() {
System.out.println(getName()+"不吃");
}
}