Acceleration in Java and two separate object properties

Trying to understand Java enhancement. Recently, strange behavior has been observed.

Example:

public class A extends B { public int i = 2; public void printI() { System.out.println("print i = " + this.i); } public static void main(String[] args) { B a = new A(); // <- upcasting here System.out.println("i = " + ai); a.printI(); } } class B { public int i = 1; public void printI() {} } //Output: //i = 1 //print i = 2 

It seems that an elevated object has two separate “i” properties. One "i" is available directly (ai), and the other using child class methods (a.printI ()).

It seems like an up-level object gets superclass properties and methods from a child class.

How can an object have two separate "i" s ?!

+1
source share
2 answers

It seems that an elevated object has two separate “i” properties.

Firstly, the terminology is worth mentioning. There is no such thing as an “object with increased interest” - and “i” is a field in each of A and B

But yes, there are two separate fields. It is not like one field "overrides" another or something like that.

It is not clear what you were trying to achieve, but the declaration of i in A shadows the declaration of i in B See section 6.4 Java Language Specifications for more information.

Please note that in almost all cases the fields should be private - at this moment hiding really does not matter, since you would not try to refer to a variable that was not declared in the class that you are encoding in anyway.

+5
source

How Java Works You have both fields “available”, they just have the same name. When you reference a subclass, it hides the version of the superclass, but it still exists.

+1
source

All Articles