1.多态的好处:
a.提高了代码的维护性(继承保证)
b.提高了代码的扩展性(由多态保证)
package com.huawei;
public class Demo2 {
public static void main(String[] args) {
creatMethod(new Cat());
}
public static void creatMethod(Animal a){
if(a instanceof Cat){
Cat c=(Cat)a;
c.catchrat();
}else if(a instanceof Dog){
Dog d=(Dog)a;
d.shout();
}
}
}
class Animal{
public void eat(){
System.out.println("動物吃");
}
}
class Cat extends Animal {
public void eat() {
System.out.println("貓吃");
}
public void catchrat(){
System.out.println("貓抓老鼠");
}
}
class Dog extends Animal{
public void eat() {
System.out.println("狗吃");
}
public void shout () {
System.out.println("狗叫");
}
}