nusCS2113-AY1920S1 / forum

Discussion forums
MIT License
9 stars 2 forks source link

Disambiguating overloaded functions #25

Closed aquohn closed 5 years ago

aquohn commented 5 years ago

Here's an issue that seems to be a little obscure on the interwebs: how does the compiler disambiguate which version of an overloaded function to use?

Consider the following simplified example, where ArgCommand is the ancestor for commands which need to take an argument.

public abstract class Command {
    public abstract void execute(DukeContext ctx);
}
public abstract class ArgCommand extends Command {
    protected String arg;
    public abstract void parse(String inputStr);
}

Then from the main Duke class we have:

void setupAndRun(String inputStr, Command cmd) {
    cmd.execute();
}
void setupAndRun(String inputStr, ArgCommand cmd) {
    cmd.parse(inputStr);
    cmd.execute();
}

I know passing the string in the first function is superfluous but this is just a simplified example. Anyway, the problem now is, if I call setupAndRun(someArgCommand), will it trigger the first or second function? In general, is the most general or most specific function matched first? Or is it just a matter of which function is written first in the file? Or will this fail to compile completely?

Jefferson111 commented 5 years ago

I think you will be unable to compile as the method signature is the same.

aquohn commented 5 years ago

Oops sorry, I made a typo. They were meant to have different method signatures, with Command for one and ArgCommand for the other.

okkhoy commented 5 years ago

Does this answer your question: https://stackoverflow.com/questions/36722057/polymorphism-doesnt-work-in-method-arguments-in-java

aquohn commented 5 years ago

Alright, so overloading is resolved at compile time by checking the context of the invocation - got it. Thanks!