Static binding and using dynamic binding
We know that static binding happens for private, static, final and overloaded methods, while dynamic binding happens for overridden methods. But what if my method is just public and not static, excessive, or overloaded.
public class Test{
public void print(){
System.out.println("hello!");
}
public static void main(String args[]){
Test t = new Test();
t.print();
}
}
Can someone explain to me what would make sense for print () as it is not overloaded or overridden.
source to share
Java will use invokevirtual
anyway to call the method (and thats dynamic) whether the method has been overridden or not. It is clearer if you look at the byte code
public static void main(java.lang.String[]);
Code:
0: new #5 // class Test
3: dup
4: invokespecial #6 // Method "<init>":()V
7: astore_1
8: aload_1
9: invokevirtual #7 // Method print:()V
12: return
line 9 shows invokevirtual. Now the JIT compiler may decide to remove dynamic dispatch for better performance.This is one of the methods used .
source to share
You get dynamic linking. The actual method test()
that is called depends on the actual type of the object not the declared type of the object. It doesn't matter that it is not overridden in your example, this method is still virtual and can be overridden.
Note that it main()
has static linking because (as a static method) the method main()
depends on the actual type of the class Test
.
source to share