简体   繁体   中英

Variable shadowing in Java, multiple cases static/non static

I have been taking a course in Java lately and we are dealing with programm outputs, compile errors etc. I have tried different codes myself, and one thing from my experiments really confused me: Firstly, the main method looks like this:

public static void main(String[] args){
     A a = new A();
     B b = new B();
     A ab = new B();

     System.out.println(a.a + " " + b.a + " " + ab.a);

}

Now I tried these different versions:

//1
public class A {
  public static int a = 1;
   public A() {
    a = 11;
   }
}
public class B extends A {
  public static int a = 2;
   public B(){ a = 22;}
}
//------------
//2
public class A {
  public int a = 1;
   public A() {
    a = 11;
   }
}
public class B extends A {
  public static int a = 2;
   public B(){ a = 22;}
}
//--------------
//3
public class A {
  public static int a = 1;
   public A() {
    a = 11;
   }
}
public class B extends A {
   public B(){ a = 22;}
}
//-----------
//4
public class A {
  public int a = 1;
   public A() {
    a = 11;
   }
}
public class B extends A {
   public B(){ a = 22;}
}

The outputs are the following:

  1. 11 22 11

  2. 11 22 11

3: 11 22 22

  1. 22 22 22

While I can understand outputs 1 and 2, 3 and 4 are really confusing to me.

For 3: The a = 22 in B, changes the value of a for the A object ab, because int a is not declared again in B?

And for 4: If int a in A is not static, and a is an object of the type A, why does aa have the value of ba? What is happening in 4, when I set the int a as not static?

Thanks in advance!

Important note: The answer for case 4 is 11 22 22

In case 3: when A ab = B() executed constructor of B set the static variable a in A so it has the value of 22.

in case 4: both classes A and B has instance field (a) (actually class B inherit this attribute from class A) and at construction time first the constructor of Class A executed and then the constructor of class B so when we have A a = B() first constructor of class A set the variable a to 11 then the constructor of class B set it to 22 static field in child class don't override static fields in parent class they just hide the static fields in parent class if you access the static the result is not depend on the type of object itself but it depend on the type of reference you use to access that object so when you write A a = B(), if A and B both has static field a, the result of aa is a in class A not a in class B because the type of reference you use to access the object here is A, while the object type itself is B.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM