何谓多态?多态可以理解为事物存在的多种体现形态。同一种事物,在不同条件下,表现为不同的结果。
举个例子,有一只猫,还有一只狗,统称为动物。当我们面前有一只猫的时候,我们说动物,那么指的就是这只猫,如果我们面前是一只狗,那么我们说动物就指的是这只狗。
多态的定义方式: 父类 父类的引用 = new 子类。父类的引用也可以接受子类对象。
我们根据父类的引用来调用子类的方法,可以大大提高程序的扩展性。
例如:
abstract class Animal
{
public abstract void eat();
}
class Cat extends Animal
{
public void eat()
{
System.out.println("eat 猫食");
}
}
class Dog extends Animal
{
public void eat()
{
System.out.println("eat 狗食");
}
}
public class PolymorphismTest {
public static void main(String[] args)
{
Animal animal1 = new Cat();
Animal animal2 = new Dog();
feedAnimal(animal1);
feedAnimal(animal2);
}
//静态方法,喂动物,接收Animal类型,执行子类方法
public static void feedAnimal(Animal animal)
{
animal.eat();
}
}
如果没有多态,那么喂动物的静态方法则需要根据各种动物,写各种eat方法。如果有新增的动物,那么改动会很大。而有了多态,我们只需要根据父类Animal的引用,调用各种动物的eat方法。
要点:
1.多态的体现:父类引用指向了子类的对象。可以是定义时声明,也可以接受。
2.多态的前提:(a)类之间有继承或者实现的关系 (b)存在方法的覆盖
3.提高了扩展性,但是注意用父类的引用使用父类存在的方法,子类实现。
//父类
class Parent
{
//eat方法
public void eat()
{
System.out.println("Parent eat");
}
}
//子类,继承父类
class Son extends Parent
{
//子类eat方法,覆写父类eat方法
public void eat()
{
System.out.println("Son eat");
}
public void play()
{
System.out.println("Son play");
}
}
//main
public class PolymorphismTest2 {
public static void main(String[] args)
{
Parent parent = new Son();
//调用eat方法
parent.eat();
//调用play方法,但是父类没有play方法,所以将引用向下转型为Son类型,有play方法,才可以调用
((Son)parent).play();
}
}
public class ParentChildTest {
public static void main(String[] args) {
Parent parent=new Parent();//100
parent.printValue();
Child child=new Child();//200
child.printValue();
parent=child;
parent.printValue();//200
parent.myValue++;
parent.printValue();//200
((Child)parent).myValue++;
parent.printValue();//201
}
}
class Parent{
public int myValue=100;
public void printValue() {
System.out.println("Parent.printValue(),myValue="+myValue);
}
}
class Child extends Parent{
public int myValue=200;
public void printValue() {
System.out.println("Child.printValue(),myValue="+myValue);
}
}原文地址:http://blog.csdn.net/puppet_master/article/details/41759101