向上转型、向下转型的作用以及用途
Opened this issue · 1 comments
styleyan commented
向上转型
也可以叫做 `"隐式转型、自动转型",是父类引用指向子类实例,可以调用子类重写父类的方法以及父类派生的方法,无法调用子类独有方法,子类型转型为大类。
package com.isyxf.test.tft;
public class Main {
public static void main(String[] args) {
Animal animal = new Animal();
// 向上转型、隐式转型、自动转型
Animal cat = new Cat();
Animal dog = new Dog();
animal.eat();
cat.eat();
dog.eat();
}
}
styleyan commented
向下转型
也可以称 "强制类型学转换",子类引用指向父类对象,此处必须进行强转,可以调用子类特有的方法,必须满足转换条件才能转换。
package com.isyxf.test.tft;
public class Main {
public static void main(String[] args) {
Animal animal = new Animal();
Animal cat = new Cat();
// 向下转型
Cat temp = (Cat)cat;
temp.eat();
temp.run();
}
}