Real vs Explicit Classes in Java

class A { public static void main(String[] args) { A a = new A(); B b = new B(); A ab = new B(); System.out.format("%d %d %d %d %d %d", ax, bx, ab.x, ay, by, ab.y); } int x = 2; int y = 3; A(int x) { this.x = x; } A() { this(7); } } class B extends A { int y = 4; B() { super(6); } 

Hey there, I just looked through some examples from my course and came across this problem that surpassed me.
I understand that this code should print "7 6 6 3 4 3"

But why is ab.y equal to 3? Isn't the "real" type of an object of class B class ab? Which then would make me believe that ab.y be 4?

+6
java
source share
1 answer

Because you are accessing fields directly, not through getter methods.

You cannot redefine fields, only methods .

Class B has a y field in addition to that found in parent class A These two fields do not interfere with each other, which is selected at compile time (by the type known to the compiler).

If you say

  A ab = new B(); 

then

  ab.y 

will be compiled to see the y field declared in class A This is not sent at runtime to the class of the real instance. It will be the same with the static method.

If you do

  B ab = new B(); 

then you get a field in class B

+8
source share

All Articles