Java

Monday, July 18, 2005

!!Overloading considered harmful(cont..)!!

(Program and Illustration)

To get to know the concept well and illustrate further the limitations faced while using Overloading, a Simple Program is used. This program has two classes:Superclass Top and Subclass Sub which inherits Top.

public class OverloadingTest {
public abstract static class Top {
public String f(Object o) {
String whoAmI = "Top.f(Object)";
System.out.println(whoAmI);
return whoAmI;
}
}
public static class Sub extends Top {
public String f(String s) {
String whoAmI = "Middle.f(String)";
System.out.println(whoAmI);
return whoAmI;
}
}
public static void main(String[] args) {
Sub sub = new Sub();
Top top = sub;
String stringAsString = "someString";
Object stringAsObject = stringAsString;
if (top.f(stringAsObject) == sub.f(stringAsString)) {
System.out.println("Hi!");
}
else {
System.out.println("Bye!");
}
}
}
Interpretations from the code:
From the above program we can get to know about the difference when we get to access the object and the string.
1.] There are two overloaded methods spread across a class hierarchy (one class inheriting from another class). This is the server code to be called by the client.
The superclass defines: String f(Object o).
The subclass defines: String f(String s).
The signatures are chosen to make both methods eligible candidates to be executed in the context of calls on the subclass instance with a String argument.
2.] The client provides two objects, reused for all calls and chosen in a way that both ov erloaded methods are potentially eligible candidates for executing the client calls.
3.] Through polymorphic assignment, the client obtains references of different types for these two instances.
4.] The client makes method calls that differ only in the different references used for making the call. In the given setup, there are 4 different call forms possible: Overloading has the method name fixed, so only the target reference type and the parameter reference type are variable. Every reference type for the target can be combined with every reference type for the argument.

(Next: Overloading and Problems with late binding & Inheritance)

0 Comments:

Post a Comment

<< Home