在子类定义的实例方法中可以通过super来访问父类中被隐藏的实例变量,如下代码。
class BeseClass{
public int a = 5;
}
public class SubClass extends BaseClass{
public int a = 7;
public void accessOwmer(){
System.out.println(a);
}
public void accessBase(){
System.out.println(super.a);
}
public static void main(String[] args){
SubClass sc = new SubClass();
sc.acessOwer(); //输出7
sc.acessBase(); //输出5
}
}
第二种是调用父类的构造器
class Base{
public double size;
public String name;
public Base(double size, String name){
this.size = size;
this.name = name;
}
}
public class Sub extends Base{
public String color;
public Sub(double size, String name, String color){
//通过super调用父类构造器初始化过程
super(size, name);
this.color = color;
}
public static void main(String[] args){
Sub s = new Sub(5.6, "测试对象", "红色");
//输出sub对象的三个实例变量
System.out.println(s.size + "--" + s.name + "--" + s,color);
}
}