在Java中访问超类的覆盖字段?

问题描述:

我在我的子类中命名了一个和我的父类相同的字段。我基本上覆盖了我父类中的字段。在Java中访问超类的覆盖字段?

如何区分字段与扩展类中具有相同名称的字段中的基类?

+1

注:此通常称为[*隐藏*](https://docs.oracle.com/javase/tutorial/java/IandI/hidevariables.html),而不是覆盖。 –

关键字super是大多数时间用于访问超类方法,大部分时间是父类的构造函数。

关键字this是用于区分类的字段与方法参数或具有相同名称的局部变量的大部分时间。

但是,您还可以使用super来访问超类的字段或this以调用方法(由于所有调用都是虚方法调用,这是多余的)或来自同一类的另一个构造方法。

以下是访问字段的用法示例。

public class Base { 

    public int a = 1; 
    protected int b = 2; 
    private int c = 3; 

    public Base(){ 

    } 
} 

public class Extended extends Base{ 

    public int a = 4; 
    protected int b = 5; 
    private int c = 6; 

    public Extended(){ 

    } 

    public void print(){ 
     //Fields from the superclass 
     System.out.println(super.a); 
     System.out.println(super.b); 
     System.out.println(super.c); // not possible 

     //Fields from the subclass 
     System.out.println(this.a); 
     System.out.println(this.b); 
     System.out.println(this.c); 
    } 
} 

public static void main(String[] args) { 
     Extended ext = new Extended(); 
     ext.print(); 
    } 

您可以随时重命名你的子类中的字段不冲突,但如果你想区分超场的方法参数或局部变量,使用super,就像使用this