0

Consider the following three Java 8 classes:

SupClass.java:

public class SupClass {
    public int id = 1;

    public int getId() {
        return id;
    }
}

SubClass.java:

public class SubClass extends SupClass {
    public int id = 2;

    public int getId() {
        return id;
    }
}

Main.java:

public class Main {

    public static void main(String[] args) {
        SupClass One = new SupClass();
        SubClass Two = new SubClass();

        SupClass Wtf = (SupClass) new SubClass();

        System.out.println("One.id: " + One.id);
        System.out.println("Two id: " + Two.id);
        System.out.println("Wtf id: " + Wtf.id);

        System.out.println("One.getId: " + One.getId());
        System.out.println("Two.getId: " + Two.getId());
        System.out.println("Wtf.getId: " + Wtf.getId());
    }
}

If you create a small project and actually run the Main class, then you would see the following result:

One.id: 1
Two id: 2
Wtf id: 1
One.getId: 1
Two.getId: 2
Wtf.getId: 2

Why do Wtf.id and Wtf.getId() produce different values? Bonus points: has it always been like that or does it differ for Java 8/9/10?

alisianoi
  • 2,003
  • 3
  • 31
  • 46
  • 3
    Because you [hide the field `id` of `SupClass` within `SubClass`](https://docs.oracle.com/javase/tutorial/java/IandI/hidevariables.html). – Turing85 May 05 '18 at 20:20
  • If so, I would expect `Wtf.id` to return 2, no? Because the `SubClass` is instantiated, so it hides the field of the `SupClass`. Then it is cast to `SupClass`, but the field is already hidden. So, in my understanding `Wtf.id` should be 2. Why am I wrong? – alisianoi May 05 '18 at 20:23
  • 1
    It has always been this way. For direct field access, it depends on the declared type of the reference - if the declared type is `SupClass` (like the `wtf` reference) Java will access the `id` field of `SupClass`. If the declared type is `SubClass` it will access the `id` field of `SubClass` – Thomas Kläger May 05 '18 at 20:25

0 Answers0