Method overloading

class Base {
  String info() {
    return "Base class";
  }
}

class Derived extends Base {
  String info() {
    return "Derived class";
  }
}


public class Handler {

  public static void main(String[] args) {
    Handler handler = new Handler();
    Base b = new Base();
    handler.handle(b); // 1
    Derived d = new Derived()
    handler.handle(d); // 2
    Base bd = new Derived()
    handler.handle(bd); // 3
  }

  void handle(Base b) {
    System.out.println("Base handling: " + b.info());
  }

  void handle(Derived d) {
    System.out.println("Derived handling: " + d.info());
  }

}

Result:

Base handling: Base class
Derived handling: Derived class
Base handling: Derived class

The choice which overloaded method to use is made at compile time – there types are Base (1), Derived (2) and Base (3) – made by explicit cast to Base.

Note that in case of miss of method void handle(Derived d), then the method handle(Base)would handle all types and the result would be:

Base handling: Base class
Base handling: Derived class
Base handling: Derived class

So in other words, if we have a type Derived which extends Base, then method handle(Base) will be executed always for object of type Base and Derived casted to Base. In case of miss of method handle(Derived), then handle(Base) will also handle object of type Derived.
Method handle(Derived) will be only used for objects of type Derived that are not casted to Base.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s