多态分为方法的 多态 和 对象 的多态:
- 方法的多态是 重载和重写
- 对象的多态分为两种:
向上转型:父类对象可以new一个其子类的对象,本质是父类的引用指向了子类的对象。在程序的执行过程中,编译是根据左边的对象进行编译,而运行时是根据右边的对象执行。
向下转型:把父类对象的 引用强转给子类的对象。注意不能是父类的对象。从逻辑上来说不能把一个大类型的对象转换为较小类型的对象,除非该大类型的对象曾指向较小类型的对象。
例如:
定义三个类:分别为Person以及其子类Student,Teacher。
public class Person {
private String name;
private int age;
public String getInfo(){
return name+"\t"+age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Person(String name,int age){
this.name=name;
this.age=age;
}
public void work(){
System.out.println("好好工作,不许偷懒");
}
}
public class Student extends Person {
public String getInfo(){
return super.getInfo()+"\t"+score;
}
public Student(String name, int age,double score) {
super(name, age);
this.score=score;
}
private double score;
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
public void work(){
System.out.println("好好学习,天天向上");
}
}
public class Teacher extends Person {
public Teacher(String name, int age,double salary) {
super(name, age);
this.salary=salary;
}
public void work(){
System.out.println("好好教学,天天赚钱");
}
public String getInfo() {
return super.getInfo()+"\t"+salary;
}
private double salary;
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
在主函数中来创建Person对象分别指向Student,Teacher类。使用类中的方法会根据不同子类调用相应的方法。
public static void main(String[] args) {
//1.声明并开辟空间
Person[] pers = new Person[5];
//2.赋值
pers[0]=new Person("段誉",20);
pers[1]=new Student("王语嫣",21, 98.5);
pers[2]=new Student("慕容复",25,59.9);
pers[3]=new Teacher("逍遥子",120,10000);
pers[4]=new Teacher("李秋水",108,29000);
//3.使用
for (int i = 0; i < pers.length; i++) {
System.out.println(pers[i].work());
}
}
父类只能调用其自身所有成员,不能调用子类中特有的成员。在程序运行时实现子类中的方法。
这就是编译看左边,运行看右边。