Monday, December 27, 2010

Override checks on run time, Overload on compile time

This is something that most people knows but sometimes forget.

Overriding is resolved against the runtime type of the object and overloading is resolved against the compile time type of the object.

To understand see the following code and what it prints:



public class Main {
    public static void main(String[] args) {
        Base a = new Derived();
        a.toOverride();
        a.overloaded(a);
    }
}
class Base{
    public void toOverride(){
        System.out.println("Override me");
    }
    public void overloaded(Base base){
        System.out.println("print  BASE");
    }
    public void overloaded(Derived derived){
        System.out.println("print  DERIVED");
    }
}
class Derived extends Base{
    @Override
    public void toOverride(){
        System.out.println("Overrided!!");
    }
}




The program prints

Overrided!!
print BASE


We can see that the variable "a" is of type Derived at runtime, but is declared with a reference to the type Base. When we invoke the toOverride method, the method in the Derived class is invoked. However when we invoke the overloaded method the method that gets called is the one that receives the Base parameter instead of the one that receives the Derived parameter.
.......................
Quick Java Facts
Top Java books...

1 comment: