Reputation: 373
We know static binding occurs for private, static , final and overloaded methods, While dynamic binding occurs for overridden methods. But what if my method is just public and it is neither static nor overriden and 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 me what binding is going to happen for print() as it is neither overloaded nor overridden.
Upvotes: 3
Views: 95
Reputation: 23349
Java will use invokevirtual
anyways to invoke the method (and thats dynamic), whether the method has been overriden 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 might decide to remove the dynamic dispatch to achieve better performance, It is one of the used techniques.
Upvotes: 2
Reputation: 15398
You get dynamic binding. The actual test()
method invoked depends on the actual type of the object not on the declared type of the object. It does not matter that it is not overridden in your example, the method is still virtual and can be overridden.
Note that main()
has static binding, because (as a static method) the main()
method depends on the actual type of the class Test
.
Upvotes: 0
Reputation: 727047
You still get dynamic binding here, because the compiler does not know that the method has no overrides. Just-in-time compiler may figure it out and optimize the call anyway, but as far as Java compiler is concerned, the binding to method print()
is dynamic.
Upvotes: 1