1

What the question says, which methods are dynamically bound in Java?

Coming from C++, if I am not mistaken, most methods are statically bound with a few exceptions.

Henry Z
  • 163
  • 8
  • 4
    Take a look at this article: http://geekexplains.blogspot.com/2008/06/dynamic-binding-vs-static-binding-in.html – Jon Lin Sep 17 '11 at 08:17
  • 2
    Java non static methods are virtual by default. The jit optimises the code to minimise the overhead associated with doing this. Eg it can inline virtual methods. – Peter Lawrey Sep 17 '11 at 09:44
  • http://download.oracle.com/javase/tutorial/javabeans/properties/bound.html http://download.oracle.com/javase/tutorial/uiswing/concurrency/bound.html – Samir Mangroliya Sep 17 '11 at 08:26

3 Answers3

4

In theory, all methods are dynamically bound, with the exception of

  • Static methods
  • Constructors
  • Private methods
  • Final methods

In practice, at runtime the JVM may choose to JIT-compile some method calls to be statically resolved, for instance if there are no loaded classes containing an overriding method.

Oak
  • 26,231
  • 8
  • 93
  • 152
3

Instance method calls are resolved at runtime, static method calls are resolved at compile time.

jeha
  • 10,562
  • 5
  • 50
  • 69
0

In general you can think of it like thie: At compile time the compiler checks the static binding. At runtime the dinamic type is checked.

for Example:

Class A{
  public void function x(){ print("x"); }
}
Class B extends A{
  public void function x(){ print("y"); }
  public void function m(){ print("m"); }
}

public static void main(){
   A a = new B();
   a.x();        //1
   a.m();        //2
   ((B)a).m();   //3
}
  • in 1 will compile because the static type of a is A and A has a function called X, but at runtime there will be recognized a B object, and printed 'y'
  • in 2 there will be a compilation error because a is of type A and the class A has no function called m.
  • in 3 there will be checked if that inheritance B->A is legal, and then if class B has an function called m.

*notice that in the last case of casting, the compiler checks only the possibility of inheritance and not that there will be a B object. for example:

A a = new A();
((B)a).m();

will compile but throw a runntime exception.

Ramzi Khahil
  • 4,932
  • 4
  • 35
  • 69