多态的概念
多态,简单来说就是:同一件事情发生在不同的对象上,会有产生不同的结果
多态的实现条件
- 必须在继承体系下
- 子类要对父类方法进行重写
- 通过父类的引用调用重写的方法
重写
public class Animal {
public String name;
public int age;
public Animal(String name) {
this.name = name;
}
public void eat() {
System.out.println(this.name + "正在吃饭");
}
public void sleep() {
System.out.println(this.name + "正在睡觉");
}
}
public class Cat extends Animal{
public Cat(String name) {
super("小猫");
}
@Override
public void eat() {
System.out.println(this.name + "正在吃猫粮");
}
}
重写方法规则:
- 子类重写父类方法时,返回值类型,方法名和参数类型必须保持一致
- 子类重写的方法返回值类型必须是父子类关系的
- 子类重写的方法访问权限不能比父类更低
- 父类被
private,static修饰的方法不能被重写
重写与重载的比较
| 区别 | 访问限定符 | 返回值类型 | 参数列表 | 绑定类型 |
|---|---|---|---|---|
| 重写 | 比父类更宽松 | 不能修改 | 不能修改 | 动态绑定 |
| 重载 | 可以修改 | 可以修改 | 必须修改 | 静态绑定 |
向上转型
向上转型,就是创建一个子类对象,使其成为父类引用
语法格式:父类类型 对象名= new 子类类型();
public class Test {
public static void main(String[] args) {
Animal dog = new Dog();
}
向下转型
当子类成为父类类型之后,可能无法调用子类特用的方法,这个时候就要用到向下转型
注意:向下转型由于类型不一致可能会抛出异常,需要用到instanceof关键字
public class TestAnimal {
public static void main(String[] args) {
Cat cat = new Cat("小猫",2);
Dog dog = new Dog("小狗", 1);
// 向上转型
Animal animal = cat;
animal.eat();
animal = dog;
animal.eat();
if(animal instanceof Cat){
cat = (Cat) animal;
cat.mew();
}
if(animal instanceof Dog){
dog = (Dog) animal;
dog.bark();
}
}
}

参与讨论
(Participate in the discussion)
参与讨论