多态:父类的引用指向了自己的子类对象,从而拥有不同的属性和方法。在JAVA中包括:运行时多态和编译时多态。
对象的多态性:动物 x = new 猫(); 动物 x = new 狗();
函数的多态性:函数overriding(重写)和overloading(重载)。
多态的前提:必须是类与类之间只有关系,要么继承或实现 ;通常还有一个前提,存在覆盖。
多态的好处:多态的出现大大的提高了程序的扩展性。
//需求:猫,狗。
//创建一个动物类
abstract class Animal {
abstract void eat();
}
//创建一个猫类并继承动物类
class Cat extends Animal {
public void eat() {
System.out.println("吃鱼");
}
public void catchMouse() {
System.out.println("抓老鼠");
}
}
//创建一个狗类并继承动物类
class Dog extends Animal {
public void eat() {
System.out.println("吃骨头");
}
public void kanJia() {
System.out.println("看家");
}
}
//多态测试类
class DuoTaiDemo {
public static void main(String[] args) {
function(new Cat());
function(new Dog());
Animal a = new Cat();// 向上转型
a.eat();
Cat c = (Cat) a;// 向下转型
c.catchMouse();
}
public static void function(Animal a) {
a.eat();
// 用于子类型有限
// 或判断所属类型进而使用其特有方法
if (a instanceof Cat) {
Cat c = (Cat) a;
c.catchMouse();
} else if (a instanceof Dog) {
Dog c = (Dog) a;
c.kanJia();
}
}
}