多态的表现形式
* 1. 必须要有继承关系, 一般会伴随着方法重写.
* 2. 父类的引用指向子类的对象.
* 格式:
* 父类类型(抽象类) 变量名 = new 子类类型();
* 接口 接口名 = new 实现类();
*
* 使用:
* 父类的引用.方法名();
* 编译的时候看父类, 运行的时候看子类;(编译看左边, 运行看右边.)
* 如果父类没有就编译报错
如:
Animal ani2 = new Cat(); ani2.eat();// 猫吃鱼(因为父类有eat的方法,所以可以直接.eat;但是如果父类没有catchMouse的方法,虽然能编译成功,但是运行时还是会出错.) //ani2.catchMouse();// 因为编译的时候看左边Animal,如果没有该方法就报错了.
* 多态的四种使用形式:
* 1. 类(抽象类)作为方法的参数传递, 传递的是该类的子类对象
* 2. 类(抽象类)作为方法的返回值, 返回的是该类的子类对象
* 3. 接口作为方法的参数, 传递的是实现类对象
* 4. 接口作为方法的返回值, 返回的是实现类对象.
* 多态的好处:
* 1.类可以作为方法的参数进行传递,无限扩展子类
如:
// public static void weiShi(Cat cat){// Cat cat = new Cat()
// cat.eat();
// }
//
// public static void weiShi(Dog dog){
// dog.eat();
// }
// 使用多态的方式对上述代码进行优化, 参数类型写成父类类型
// 父类的引用作为方法的参数
// 这个方法不需要做任何改变,Animal可以无限扩展子类.
public static void weiShi(Animal ani) {// Animal ani = new Dog()
ani.eat();
}
public static void main(String[] args) {
weiShi(new Cat());
weiShi(new Dog());
}
* 2.类可以作为方法的返回值.
如:
/*
* 自动出售动物的机器
*/
// public static Cat getAnimal1(){
// return new Cat();
// }
//
// public static Dog getAnimal2(){
// return new Dog();
// }
// 将上面的代码进行优化
// Animal ani = new Cat();
public static Animal getAnimal(int select){
if(select == 1){
return new Cat();
}else{
return new Dog();
}
}
public static void main(String[] args) {
Animal ani = getAnimal(1);
ani = getAnimal(2);
ani.eat();
}
* 3.接口作为方法的参数: 传递的是接口的实现类对象
//1.接口作为方法的参数传递
public static void zhaoPin(SmokerInter si){
si.smoke();
//si.study();
// 调用特有方法
if(si instanceof Student){
Student stu = (Student)si;
stu.study();
}
if(si instanceof Worker){
Worker work = (Worker)si;
work.work();
}
if(si instanceof Pig){
Pig pig = (Pig)si;
pig.gongDi();
}
System.out.println("=========");
}
* 4.接口作为方法的返回值: 返回的是接口的实现类对象
// 模拟驾校培训开车的学生
public static DriverInter getDriver(){
//return new Student();
//return new Pig();
return new SmallPig();
}
多态的向上转型和向下转型(向下转型的前提必须是先向上转型)
Plane p = new Battleplane();
System.out.println("===向上转型");
p.fly();
if(p instanceof Battleplane){// 如果p是Battleplane的对象返回true, 否则返回false
Battleplane ba1 = (Battleplane) p;
System.out.println("===向下转型");
ba1.fire();
ba1.fly();
}