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,以“可以使用”或“正在使用”。