一.多态的定义
何谓多态?多态可以理解为事物存在的多种体现形态。同一种事物,在不同条件下,表现为不同的结果。
举个例子,有一只猫,还有一只狗,统称为动物。当我们面前有一只猫的时候,我们说动物,那么指的就是这只猫,如果我们面前是一只狗,那么我们说动物就指的是这只狗。
多态的定义方式: 父类 父类的引用 = 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();
}
}
要点:
1.定义一个子类对象并用父类引用时(或者直接将子类对象赋值给父类引用时),称为向上转型,可以直接转型。
2.从父类引用转向为子类引用,称为向下转型,不能直接转型,需要用强制转换。
3.注意自始至终对象是没有转换的,转换的都是引用!!!
三.多态的特性
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);
}
}
要点:
1.多态中父类和子类有同名变量时,看的是引用类型的变量,根据引用类型的变量判断使用子类还是父类中的变量。
2.多态中父类和子类中有同名方法时,看的是对象类型。对象是子类的,调用的是子类的方法;对象是父类的,调用的是父类的方法。
3.多态中父类和子类有相同的静态时,看到是引用类型。