Static Java Variable Search Instance

class A {int x = 5;} class B extends A {int x = 10;} class D { public static void main(String[] args){ A b0 = new B(); System.out.print(b0.x); } } 

I am wondering why this code prints 5 instead of 10.

If I write the following instead, converting the x variables to methods, it works more as I expected, and yields 10, since at compile time it just checked to see if the static type is b0 A, the method is x, and then uses dynamic type b0, B, to run x.

 class A {int x() {return 5;}} class B extends A {int x() {return 10;}} class D { public static void main(String[] args){ A b0 = new B(); System.out.print(b0.x()); } } 

My theory is that instance variables look statically unlike methods, but I'm not sure why this would be.

Thanks!

+5
source share
3 answers

In B field x of A shaded (hidden) not redefined. To answer "why it will be" links to documents here and here . The compiler will select one of two x instances according to the type of the containing object. And b0 is of type A

  A b0 = new B(); 

When you define methods (getter), on the other hand, they can override methods with the same signature in the parent class. Another nasty surprise is that the field of the parent class is obscured, even if it is different from another.

Shadowing members is considered bad practice, as it confuses developers.

+4
source

Since you are accessing the variable x from class A , since b0 is defined as A It is called hiding a variable, and not because you might suspect a variable override, which is not possible in java. You will get the expected result if you accessed x from b0 using typeCast.

 A b0 = new B(); System.out.print(((B)b0).x); 

Using typeCast, you will now access the variable x from class B

for more information you can read JLS 8.3

+4
source

Static fields are not inherited, they do not override each other, they are shadow of each other. When directly accessing a static field with the same name in your case, the superclass field hides another field, and you have two int Xes, but one of the superclass is not hidden and will not be selected. Even better, when you call another instance of the same method and access the same static field, that is, when things get very strange. Static fields are combined together and you can end up with X being 5 + 5 = 10.

On the other hand, if you inherit a non-stationary field from a superclass, there is no problem with its different value in the subclass, because the subclass can override the non-static super member.

Static variables and inheritance are bad, it breaks polymorphism, where you least expect it. (In fact, if you understand the concepts of your language, you expect this, but other people cannot)

+3
source

Source: https://habr.com/ru/post/1234996/


All Articles