2 多态
2.1 多态是什么
多态在我看来就是不同对象做同一件事,产生的结果不一样。
2.2 多态的实现条件
1. 必须在继承体系下。
2. 子类必须要对父类中方法进行重写。
3. 通过父类的引用调用重写的方法。
2.3 重写
方法重写的格式
1.方法的名字相同
2.返回值相同
3.参数列表相同【顺序&&个数&&类型】
重写的限制条件
1.必须具有继承关系。
2.访问权限不能比父类中被重写的方法的访问权限更低。
3.父类被static、private,final修饰的方法、构造方法都不能被重写。
重写与重载的区别
2.4 向上转型
向上转型的使用场景
直接赋值
方法传参
方法返回
public class Animal {
public String name;
public int age;
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
}
public class Dog extends Animal {
public Dog(String name, int age) {
super(name, age);
}
}
用以上代码举例
1. 直接赋值
Animal animal = new Dog("大黄",2);
2. 方法传参
public static void func (Animal animal) {
}
Dog dog = new Dog("大黄",2);
func(dog);
3. 方法返回
public static Animal func () {
Dog dog = new Dog("大黄",2);
return dog;
}
func();
向上转型的优点:让代码实现更简单灵活。
向上转型的缺点 :通过父类的引用,无法调用子类特有的方法,只能调用父类自己的方法。
如果对父类的方法在子类里进行重写,再通过父类的引用调用该方法,结果实行的是子类的该方法
这种情况叫动态绑定。
2.5 向下转型
向下转型的风险
为了避免以上情况,我们可以使用instanceof 关键字
Animal animal = new Dog("大黄",2);
if(animal instanceof Bird) {
Bird bird = (Bird) animal;
bird.fly();
}else {
System.out.println("animal instanceof Bird NOT!!!");
}
2.6 多态优点和缺点
优点:
1.能够降低代码的 "圈复杂度", 避免使用大量的 if - else
2.拓展性强
public class Shape {
public void draw() {
System.out.println("画一个形状...");
}
}
public class Circle extends Shape{
public void draw() {
System.out.println("画一个⚪");
}
}
public class Circle extends Shape{
public void draw() {
System.out.println("画一个⚪");
}
}
public class Circle extends Shape{
public void draw() {
System.out.println("画一个⚪");
}
}
缺点:
代码的运行效率降低。