以父类的变量访问子类对象的成员
以父类声明变量,并将它指向用子类新建的对象。
此时使用此变量可调用 子类中覆盖父类中的成员函数,或子类中没有而父类中有的成员函数
用法:
利用父类的数组变量来访问子类对象的成员
(1)先创建父类的数组变量;
(2)创建子类对象并放入数组,利用数组元素来访问子类的内容。
例
package com;
public class JavaTest {
public static void main(String ar[])
{
TFather tc = new TChild();
tc.show();
System.out.println(tc.num);
System.out.println(tc.getClass());
tc.showF();
//tc.showC();
}
}
class TFather{
protected int num = 3;
public TFather(){
}
public void show(){
System.out.println("父类show");
}
public void showF(){
System.out.println("子类没有");
}
}
class TChild extends TFather{
protected int num = 4;
public TChild(){
}
public void show(){
System.out.println("子类show");
}
public void showC(){
System.out.println("子类没有");
}
}
结果:
子类show
3
class com.TChild
子类没有
执行tc.showC()时会报错,
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method showC() is undefined for the type TFather
at com.JavaTest.main(JavaTest.java:10)