结论:向上转型时,声明的是父类的引用,但是执行的过程中调用的是子类的对象,程序会去寻找父类的method方法以及子类的method方法:
1. 如果父类没有,子类有,会报错。
2. 如果父类有,子类没有,调用父类method。
3. 如果父类有,子类也有,调用子类method。
public class Father {
public void method() {
System.out.println("父类方法,对象类型:" + this.getClass());
}
}
public class Son extends Father {
public static void main(String[] args) {
Father sample = new Son();//向上转型
sample.method();
}
}
结果:“父类方法,对象类型:class Son”
public class Son extends Father {
public void method() {
System.out.println("子类方法,对象类型:" + this.getClass());
}
public static void main(String[] args) {
Father sample = new Son();//向上转型
sample.method();
}
}
结果:“子类方法,对象类型:class Son”
在向上转型的情况下,对象的方法可以找到子类,而对象的属性还是父类的属性。
代码如下:
public class Father {
protected String name="父亲属性";
public void method() {
System.out.println("父类方法,对象类型:" + this.getClass());
}
}
public class Son extends Father {
protected String name="儿子属性";
public void method() {
System.out.println("子类方法,对象类型:" + this.getClass());
}
public static void main(String[] args) {
Father sample = new Son();//向上转型
System.out.println("调用的成员:"+sample.name);
}
}
结果:“调用的成员:父亲属性”
这个结果表明,子类的对象(使用父类的引用)调用到的是父类的成员变量。
那如果需要调用子类的成员变量name,该怎么做?最简单的办法是将该成员变量封装成方法getter形式。
代码如下:
public class Father {
protected String name = "父亲属性";
public String getName() {
return name;
}
public void method() {
System.out.println("父类方法,对象类型:" + this.getClass());
}
}
public class Son extends Father {
protected String name="儿子属性";
public String getName() {
return name;
}
public void method() {
System.out.println("子类方法,对象类型:" + this.getClass());
}
public static void main(String[] args) {
Father sample = new Son();//向上转型
System.out.println("调用的成员:"+sample.getName());
}
}
结果:“调用的成员:儿子属性”,因为这相当于前面例子的方法重写。
另外,也可以以实现接口的方式进行向上转型
代码如下:
interface A {
abstract void f();
}
class B implements A{
public void f(){
System.out.println("bbbbb");
}
}
class C implements A{
public void f(){
System.out.println("ccccc");
}
}
public class Son {
public static void main(String[] args){
A[] a = new A[2];
a[0] = new B();
a[1] = new C();
for (int i=0;i<a.length;i++){
a[i].f();
}
}
}
ccccc”