一:多态:Polymorphic
//多态
public class Polymorphic01 {
public static void main(String[] args){
//使用多态实例化子类
//把一个子类对象付给父类对象,这个是时候,只能调用父类的方法
Animal a = new Dog();
a.age = 20;
a.sex ="公";
a.breed = "金毛";
a.eat();
a.sleep();
}
}
class Animal{
String breed; //品种
int age; //年龄
String sex; //性别
public void eat(){
System.out.println("吃...........");
}
public void sleep(){
System.out.println("睡...........");
}
}
class Dog extends Animal{
String furColor; //毛色
public void run(){
System.out.println("跑...........");
}
@Override
public void eat() {
System.out.println("狗开始大口大口的吃狗粮");
}
}
二:多态的应用:PolymorphicUse & instanceofKeyWord
//多态的应用
public class PolymorphicUse02 {
public static void main(String[] args) {
Master m = new Master();
m.name ="小明";
Dog dog = new Dog();
m.feed(dog);
System.out.println("请输入你要买的动物");
System.out.println("1、小狗 ,2、啥也没有");
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
Animal animal = m.buy(choice);
if (animal!=null){
System.out.println("购买成功");
//将父类引用中的真实子类对象强制转回本身类型,称为向下转型
//注意:只有转换回子类真实类型,才可以调用子类独有的属性和方法
//如果不是真实的类型会出现异常:
//Exception in thread "main" java.lang.classCallException
//向下转型时,如果父类引用中的子类对象类型和目标类型不匹配,则会发生类型转换异常
if(animal instanceof Dog){
Dog dog1 = (Dog) animal;//强转成功
dog1.run();
}
}else{
System.out.println("没有其他东西");
}
//父类引用中保存真实的子类对象称为向上转型(多条的核心概念)
//注意:仅可以调用Animal中的所声明的属性和方法
// Animal animal = new Dog();
}
}
class Master{ //主人类
String name;
//使用多态
public void feed(Animal animal){
System.out.println(this.name +"喂食");
animal.eat();
}
public Animal buy(int type){
Animal animal = null;
if (type == 1){
animal = new Dog();
}else {
System.out.println("啥也没有");
}
return animal;
}
}



