java super for field
为什么java super for field,java,super,Java,Super,为什么super对类C中的i字段没有影响? 输出是012,但是为什么不321,因为类B扩展了类C public class C { protected int i; public C(int i){ this(i,i); System.out.print(this.i); this.i=i; } public C(int i, int j) { System
super
对类C
中的i
字段没有影响?
输出是012
,但是为什么不321
,因为类B
扩展了类C
public class C {
protected int i;
public C(int i){
this(i,i);
System.out.print(this.i);
this.i=i;
}
public C(int i, int j) {
System.out.print(this.i);
this.i=i+j;
}
public C(){
this(1);
System.out.print(i);
}
public static void main(String[] args) {
C c=new C();
}
}
public class B extends C{
public B(){
super.i=3;
}
public static void main(String[] args){
C c=new B();
}
}
super
可用于访问重写的方法。在您的场景中,i
是B的继承成员
如果您重写了B中在C中定义的方法,您可以使用super关键字从B中调用它。
super.i
只是引用这个.i
(或者简单地说是i
),因为类B
没有声明它自己的i
版本,所以它已经从C
继承了字段
public B(){
super.i=3; // the super here does not do anything
}
构造函数需要做的第一件事是调用一个超级构造函数。这相当于:
public B(){
super();
i=3;
}
如您所见,超类
C
中的代码在i
设置为3之前执行。这就是它打印旧值的原因。它非常简单。这就是正在发生的事情:
B Constructor is called.
B doesn´t have an explicit super constructor call- so implicity call super().
C() Constructor is called -> call C(int)
C(int) Constructor is called -> call C(int,int);
C(int, int) is called. print i. i only has the default value yet so print ->0
C(int, int) does increment i by j, which at this point is 1+1 = 2
C(int) Constructor callback, as C(int, int) is done, print i = 2
C(int) sets i = 1 and prints i = 1.
B() callback as C() is done. set instance variable i to 3.
正如您所看到的,您有一个不同的输出作为021
,这就是所有发生的情况
我不知道你最初的意图是什么,但是super
可以有不同的含义
在构造函数中,您通常使用super
访问父构造函数
通过执行super.i
操作,您只能访问父类的实例变量i
您可以通过执行
super.testMethod()
调用父类中的方法testMethod
,是否确实需要使用不同的标题多次发布问题?相同的问题today@Andreas:嗯,这不是同一个问题,这是一个后续问题。@Thilo不太可能。与super
关键字相关的任何内容都会在打印后发生,对结果绝对没有影响。请在B
的构造函数中将其设置为3
后尝试打印super.i
此.i,以“可以使用”或“正在使用”。