1.什么是多态
多态: 一类事物的多种形态 比如: 工作人员,有销售员,收银员,会计员等多种形态 动物,有猫,狗,猪等多种形态 人,有学生,老师,班主任等多种形态 多态的前提: 必须有继承关系/实现关系 必须有方法的重写[如果不重写方法,多态也是可以的,但是是没有意义的!!!] 多态的代码体现: 父类类型的变量 指向 子类类型的对象 比如: Worker w = new Sales(); Animal a = new Dog(); Person p = new Teacher();
2.多态的好处[重点]
1.多态调用方法时的特点: 编译看父,运行看子 2.多态的好处在于提高代码的扩展性 /** * 工作人员类 */ public class Worker { public void work(){ System.out.println("work..."); } } /** * 收银员 */ public class Cashier extends Worker{ @Override public void work() { System.out.println("收钱~~~"); } } /** * 销售员 */ public class Sales extends Worker{ @Override public void work() { System.out.println("带货~~~"); } } /** * 会计员 */ public class Accountant extends Worker{ @Override public void work() { System.out.println("算钱~~~"); } } public class TestDemo { public static void main(String[] args) { //创建一个多态 // Worker w = new Cashier(); //编译阶段,看父类 //运行阶段,看子类 // w.work(); //调用show方法 Cashier cc = new Cashier(); show(cc); Sales ss = new Sales(); show(ss); Accountant aa = new Accountant(); show(aa); } //使用多态,解决扩展性问题 public static void show(Worker w){ //Worker w = new Cashier(); //Worker w = new Sales(); //Worker w = new Accountant(); System.out.println("开始工作..."); w.work(); } }
3.多态的弊端
多态调用方法时候,编译看父,运行看子 换句话说就是,多态只能调用子父类都有的那个方法,如果这个方法是子类特有的,在多态情况下是不能调用的! /** * 工作人员类 */ public class Worker { public void work(){ System.out.println("work..."); } } /** * 会计员 */ public class Accountant extends Worker{ @Override public void work() { System.out.println("算钱~~~"); } //子类的特有方法 public void touSui(){ System.out.println("xxx...."); } } public class TestDemo { public static void main(String[] args) { //使用多态 调用Accountant对象的特有方法 Worker ww = new Accountant(); ww.touSui(); // 报错的,因为多态的情况不能调用子类特有的方法 } }
4.多态弊端的解决方案
向下转型: Worker ww = new Accountant(); //向上转型(多态) //向下转型之前,我们必须判断 if(ww instanceof Accountant){ //instanceof 用于判断某个对象到底是不是我们需要的那个类型的对象 Accountant tt = (Accountant)ww; //向下转型 tt.touSui(); } 类比一下基础的强制类型转换: double d = 10; //自动转换 int num = (int)d; //强制转换
5.多态的表达方式,编译看父,运行看子
多态:任何能找到的方法一定是由引用的类型所决定的,具体执行什么类型是由引用类型指向的对象决定。
例如:
public static main(String[]arr){
Penson p =new Student();
p.test();
}
Person(){
test(){
Systen.Out.println("父类的方法");
}
}
Student extends Person(){
test(){
Systen.Out.println("我是子类的方法");
}
study(){
Systen.Out.println("好好学习天天向上");
}