Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Java Dynamic Binding

Tags:

java

core

Please tell the reason for output we are getting.

As per me, with b.getx() we will get the reference id of object of B and b.getx().x should get value of 10 but when I run this program the output is 5.

class Base {
  int x = 5;
  public Base getx() {
    return new Base();
  }
}

class Child extends Base {
  int x = 10;
  public Child getx() {
    return new Child();
  }

  public static void main(String ...s) {
    Base b = new Child();
    System.out.println(b.getx().x);
  }
}
like image 206
Sharda Prasad Jaiswal Avatar asked Dec 27 '22 03:12

Sharda Prasad Jaiswal


1 Answers

Field accesses (unlike method calls) are not subject to runtime dynamic dispatch, they're resolved purely based on compile-time types.

The variable b is of compile-time type Base, therefore b.getx() is also of compile-time type Base, and so b.getx().x will be compiled into an access of Base's x field, not Child's. This is confirmed by looking at the output of javap for the main method:

public static void main(java.lang.String[]);
  Code:
   0:   new #3; //class Child
   3:   dup
   4:   invokespecial   #4; //Method "<init>":()V
   7:   astore_1
   8:   getstatic   #5; //Field java/lang/System.out:Ljava/io/PrintStream;
   11:  aload_1
   12:  invokevirtual   #6; //Method Base.getx:()LBase;
   15:  getfield    #7; //Field Base.x:I
   18:  invokevirtual   #8; //Method java/io/PrintStream.println:(I)V
   21:  return

you can see that b.getx().x was compiled into a getfield instruction for Base.x specifically.

like image 111
Ian Roberts Avatar answered Dec 28 '22 16:12

Ian Roberts