向上转型
Father father = new Son();
这里的father可以调用父类中的方法,不可以调用子类中的方法,如果子类中重写了父类中的方法,那调用的就是子类中的方法。
向下转型
Son son = (Son) father
这里的son可以调用子类中的方法。
public class Human {
public void sleep() {
System.out.println("Human sleep..");
}
public static void main(String[] args) {
Human h = new Male();// 向上转型
Human h1 = new Human();
//h.speak();此时需要向下转型,否则不能调用speak方法。
Male m = (Male) h;
m.speak();
/**Male m1 = (Male)h1;
m1.speak(); 此时会出现运行时错误,所以可以用instanceOF判断*/
if (h1 instanceof Male){
Male m1 = (Male)h1;
m1.speak();
}
}
}
class Male extends Human {
@Override
public void sleep() {
System.out.println("Male sleep..");
}
public void speak() {
System.out.println("I am Male");
}
}