public class Do { public void doSomething(Object arg) { System.out.println("Do " + arg.toString()); } }
We then extend it in the following class:
public class DoDifferently extends Do { public void doSomething(Object arg) { System.out.println("Do different " + arg.toString()); } public void doSomething(String arg) { System.out.println("Do different string " + arg.toString()); } }
Now let's use these classes in our program:
Do o = new Do(); o.doSomething("x");
executes the Object method.
DoDifferently o2 = new DoDifferently(); o2.doSomething("x");
executes the String method because it is more specific.
What about the following code?
Do o3 = new DoDifferently(); o3.doSomething("x");
It will execute the Object method, because Java uses the reference type to determine which method to call.
What about Groovy?
The code above is also valid in Groovy.
The String method is always executed when available, because Groovy uses the most specific method for the argument type, determined dynamically at run-time.
No comments:
Post a Comment