Java – referencing a subclass field if its instance is assigned to a super class reference and the fields have the same name and default access modifier

Question:

While studying inheritance and polymorphism in java, I came across this example:

class A {
 int a = 5;
 String doA() {
  return“ a1“;
 }
 protected static String doA2() {
  return“ a2“;
 }
}
class B extends A {
 int a = 7;
 String doA() {
  return“ b1“;
 }
 public static String doA2() {
  return“ b2“;
 }
 void go() {
  A myA = new B();
  System.out.print(myA.doA() + myA.doA2() + myA.a);
 }
 public static void main(String[] args) {
  new B().go();
 }
}

Result of program execution: "b1 a2 5"

  1. b1 – it's clear here. the actual type of the class is B, through dynamic binding the compiler invokes the doA() method defined in class B.

  2. a2 – the doA2() method is defined as static, accordingly, earlier binding occurs, the compiler calls the method of class A, not the instance

  3. 5 – this is where the magic happens for me. why not 7? variable is not static and not final? the actual type of class B

Answer:

A myA = new B();
^
Because fields in Java are not polymorphic, a pointer class is used accordingly, in this case it is class A .

Regarding methods: in Java all methods are virtual, so dynamic (or, as it is also called, later) binding is used. Therefore, at runtime, the JVM determines the type of the B object pointed to by the myA pointer and calls the appropriate implementation of the B class doA() method.

Scroll to Top