views:

73

answers:

4

I read in "Thinking in java" in chapter "Polymorphism" about the concept of "Late binding" , i just wanna know if my understanding of this concept is true

Procedural languages know where is the function to execute before run-time for instance

if(condition){func1();}else{func2();}

So the address of each possible function is known exactly and before the program runs , so it is compiled easily , but in OOLs examine this code ,,

makeItSpeak(Animal a ){
  a.speak();
}

While a may be a dog , a cat or any other Animal type , and because we initialize objects at run-time , so we must pass the argument upon which we run speak at run-time , so this is late binding which occurs at run-time ....

IS THAT TRUE ??

+4  A: 

Yes, and it's implemented using a virtual method table.

In your example speak() is a virtual (abstract) method that doesn't have a physical address. At runtime, based on the type of the concrete Animal subclass, the runtime figures out which implementation of speak() to invoke by referring the virtual method table.

oksayt
+2  A: 

Yes. For example,

class A {
  void a() { System.out.println("A"); }
}

class B extends A {
  void a() { System.out.println("B"); }
}

class C {
  public static void main (String[] args) {
    A anA = new B();
    anA.a();  // This will print B
  }
}

Even though the variable anA is of type A, the instance is B which can only be determined at runtime.

The gotcha in this rule is static methods, which get bound at compile time, so watch out.

leonm
+1  A: 

Yes you are correct. In the example you have given, the correct speak() to be called depends on the type of object which will be known at run time. Only when you declare a method as final it is subject to early binding.

Sagar V
Yea , because in this case we know the address of the method in advance , the reason is we know that the wanted method is the super class's one , is that true ?
3m masr
@3m masr: When you declare a method as final you are making sure that the method will not be overridden further. Hence there is no question of what object handle will be used and so the compiler will optimize.
Sagar V
This only applies to the type that declares the final keyword and its descendants though. If B extends A, A defines a method foo() and B overrides it with a final implementation, then when faced with A a.foo() at runtime, late binding will still be necessary.
oksayt
A: 

Yes, you got it right. It makes code more extensible and powerful.

fastcodejava