Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Reflection and Late Binding in java with real time examples

While studying Java tutorials, Reflection and Late Binding have confused me. In some tutorials, they have written that they are both the same, and that there isn't any difference between Reflection and Late Binding. But other tutorials say that there is a difference.

I am confused, so can someone please explain what Reflection and Late Binding are in Java, and if posible, please give me some real world examples of both.

Thanks..

like image 589
Kanika Avatar asked Jan 24 '12 09:01

Kanika


1 Answers

Java uses late-binding to support polymorphism; which means the decision of which of the many methods should be used is deferred until runtime.

Take the case of N classes implementing an abstract method of an interface (or an abstract class, fwiw).

public interface IMyInterface {

    public void doSomething();    
}

public class MyClassA implements IMyInterface {

    public void doSomething(){ ... }
}

public class MyClassB implements IMyInterface {

    public void doSomething(){ ... }
}

public class Caller {

    public void doCall(IMyInterface i){
        // which implementation of doSomething is called?
        // it depends on the type of i: this is late binding
        i.doSomething(); 
    }
}

Reflection is used instead to describe code which is able to inspect other code, ie. to know which methods or attributes are available in a class, to call a method (or load a class) by name, and doing a lot of very interesting things at runtime.

A very nice explaination of reflection is here: What is reflection and why is it useful?

like image 105
Savino Sguera Avatar answered Sep 30 '22 16:09

Savino Sguera