目录
一、什么是多态
二、多态实现的条件
三、实例分析
四、多态应用之一(多态数组)
五、多态参数
一、什么是多态
在Java中,多态是面向对象编程中的一个重要概念,它允许不同类型的对象对同一方法进行不同的实现。具体来说,多态性是指的是通过父类的引用变量来引用子类的对象,从而实现对不同对象的统一操作。
二、多态实现的条件
1.继承关系
存在继承关系的类之间才能够使用多态性。多态性通常通过一个父类的引用指向子类的对象。
2.方法重写
子类必须重写(override)父类的方法。通过在子类中重新定义和实现父类的方法,可以根据子类的特点行为改变这个方法的行为。
3.父类引用指向子类对象
使用父类的引用变量来引用子类对象。这样可以实现对不同类型的对象的统一操作,而具体调用哪个子类的方法会在运行时多态决定。
三、实例分析
public class JiCheng {public static void main(String[] args) {Animal animal = new Cat();animal.eat();}
}class Animal {void eat() {System.out.println("动物捕食");}
}class Cat extends Animal {@Overrideprotected void eat() {System.out.println("小猫吃鱼");}
}class Dog extends Animal {@Overridepublic void eat() {System.out.println("小狗吃骨头");}
}
首先要明白,多态是针对方法的来说的
我们看,Cat类和Dog类继承自Animal类,并重写了eat方法。常说的“编译看左边,运行看右边”是说,animal作为父类的引用,它能调用的方法在编译时就已经确定了,它作为父类的引用,父类的所有方法,都可调用。运行看右边,是指,运行时,具体的方法,是看到底animal是什么类型的对象,上例可知,animal本质是Cat类的对象,所以实际效果是调用Cat类的方法。如果说,Cat类没有重写父类方法,则向上调用父类的方法。
这里涉及到Java的动态绑定,父类对象的引用绑定子类方法
对于子类中一些特有的方法,我们要让他回归本源,也就是强制转换为Cat,回归自我,右边类型是Cat类,左边也是Cat类引用接收,这里注意:我们只能强转父类的引用,不能强转父类对象,还有,不能强转为Dog,因为它本质是Cat类。
如果是,调用属性:则父类引用调用的是父类的属性,属性没有多态一说;
public class JiCheng {public static void main(String[] args) {Animal animal = new Cat();animal.eat();Cat cat = (Cat) animal;cat.jiao();}
}class Animal {void eat() {System.out.println("动物捕食");}
}class Cat extends Animal {void jiao() {System.out.println("miaomiaomiao~");}@Overrideprotected void eat() {System.out.println("小猫吃鱼");}
}
四、多态应用之一(多态数组)
public class DuoTaiShuZu {public static void main(String[] args) {Person[] people = new Person[5];people[0] = new Person();people[1] = new Teacher();people[2] = new Student();for (int i = 0; i < 5; i++) {if (people[i] instanceof Person) {people[i].say();} else if (people[i] instanceof Student) {Student person = (Student) people[i];person.study();} else if (people[i] instanceof Teacher) {((Teacher) people[i]).teach();}}}}class Person {String name;int age;void say() {System.out.println("人类可互相交流");}
}class Teacher extends Person {@Overridevoid say() {System.out.println("老师说要好好学习");}void teach() {System.out.println("老师教学生");}
}class Student extends Person {@Overridevoid say() {System.out.println("学生说要适当放松");}void study() {System.out.println("学生学知识");}
}
五、多态参数
方法定义形参为父类类型,实参允许为子类类型;
public class Test1 {public static void main(String[] args) {Test1 test1 = new Test1();Student student = new Student();Teacher teacher = new Teacher();test1.shitang(student);test1.shitang(teacher);}void shitang(Person a) {if (a instanceof Teacher) {((Teacher) a).teach();return;}a.eat();}
}class Person {void eat() {System.out.println("是个人就要吃饭");}
}class Student extends Person {@Overridepublic void eat() {System.out.println("学生在学生食堂吃饭");}void study() {System.out.println("学生上课");}
}class Teacher extends Person {@Overridepublic void eat() {System.out.println("老师在员工食堂吃饭");}void teach() {System.out.println("老师教书");}
}