看代码吧!
package com.mythinking;
public class MyThinking05 {
public static void main(String[] args) {
Father father = new Father(); //编译类型是Father,运行类型也是Father
// father.f(); //报错,父类没有子类的f()这个方法,编译器提示Cannot resolve method 'f' in 'Father'
Father father1 = new Son(); //编译类型是Father,运行类型是Son,这里向上转型了
// father1.f(); //报错,编译器提示Cannot resolve method 'f' in 'Father'
((Son)father1).f(); //要向下转型才能调用子类的f()方法
// int n1 = father1.n2; //报错,编译器提示Cannot resolve symbol 'n2'
int n2 = ((Son) father1).n2; //要向下转型才能访问子类的f()方法
}
}
class Father {
public int n1 = 1;
}
class Son extends Father{
public int n2 = 2;
public void f(){
System.out.println("Son");
};
}