Core Java Dynamic Binding

Please provide the reason for the withdrawal we receive.

Like me, with b.getx () we get the reference identifier of object B and b.getx().x should get the value 10, but when I run this program, the output will be 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); } } 
+4
source share
4 answers

Access to fields (unlike method calls) is not subject to dynamic scheduling of runtime, they are allowed solely on the basis of compilation time types.

The variable b has the Base compilation time type, therefore b.getx() also refers to the Base compilation time type, and therefore b.getx().x will be compiled to access the base field x , not the child. This is confirmed by looking at the javap output 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 the getfield command for Base.x

+8
source

Dynamic binding basically means that the actual implementation of the method is determined at run time, and not at compile time. And so its called dynamic binding - because the method that will be run is selected at runtime. Dynamic binding is also known as late binding.

+1
source

Base b = new Child(); is a runtime solution and dynamic binding rules (polymorphism at runtime), all methods associated with this must be bound at runtime, therefore ...

 public Base getx() { return new Base(); } 

that the strings return a new instance of the base class, and you just call the variable in that instance.

+1
source

Dynamic linking is a runtime process for viewing a declaration at runtime. It is also known as late binding, in which invocation of an overridden method is allowed at run time, rather than at compile time. In an object-oriented system method, redefinition (dynamic polymorphism) is performed at run time. When overriding one method with another, the signatures of the two methods must be identical.

Example:

 class Animal{ public void eat(){ System.out.println("Animals voice"); } public void go(){ System.out.println("Animals can walk"); } } class Dog extends Animal{ public void go(){ System.out.println("Dogs can walk and run"); } public void eat(){ System.out.println("Dogs can eat a wide range of foods"); } } 
0
source

Source: https://habr.com/ru/post/1480978/


All Articles