在 Java 中访问超级 class 的覆盖字段?
Access overwritten fields of super class in Java?
我在我的 subclass 中命名了我的字段之一,与我的 superclass 中的相同。我基本上已经覆盖了 parent class.
中的字段
如何区分基本class字段和扩展class中的同名字段?
关键字 super
大多数时候与访问 superclass 方法结合使用,大多数时候是来自父 class 的构造函数。
关键字this
大多数时候用来区分class的字段和同名的方法参数或局部变量。
但是,您也可以使用 super
访问 superclass 或 this
的字段来调用方法(这是多余的,因为所有调用都是虚拟方法调用),或者来自同一个 class.
的另一个构造函数
这是访问字段的用法示例。
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();
}
您可以随时重命名子class中的字段以避免冲突,但如果您想将方法参数或局部变量与超class字段区分开来,请使用super
就像你会使用 this
我在我的 subclass 中命名了我的字段之一,与我的 superclass 中的相同。我基本上已经覆盖了 parent class.
中的字段如何区分基本class字段和扩展class中的同名字段?
关键字 super
大多数时候与访问 superclass 方法结合使用,大多数时候是来自父 class 的构造函数。
关键字this
大多数时候用来区分class的字段和同名的方法参数或局部变量。
但是,您也可以使用 super
访问 superclass 或 this
的字段来调用方法(这是多余的,因为所有调用都是虚拟方法调用),或者来自同一个 class.
这是访问字段的用法示例。
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();
}
您可以随时重命名子class中的字段以避免冲突,但如果您想将方法参数或局部变量与超class字段区分开来,请使用super
就像你会使用 this