Let's say I got the following, I would even call it pseudo-code
public class someClass {
public someClass{
example("Hello Stackoverflow");
}
@Override
public void example(){
System.out.println("Hello World");
}
public void example(String Hello){
System.out.println(Hello);
}
}
In this code the method public void example(String Hello)
would be called instead of the public void example()
method. How is the compiler working in this case ? The compiler has to decide which method to call in this case, because they got the same name. Is there something like an order e.g. first try @Override method, if that's not working go for the normal one. Or how does that work ?
No, what you've shown isn't overriding at all - it's overloading. (The use of the @Override
annotation is obviously to do with overriding, but it's incorrect used here - there's no superclass method to override.)
Overriding is when a method signature is declared in a superclass, and then overridden in a subclass (with the same signature). The method implementation is chosen at execution time based on the execution-time type of the object you call it on.
Overloading is when more than one method is present with the same name, but different signatures. When invoking the method, the correct signature is picked at compile time based on the compile-time types of the arguments to the method.
For example:
public void foo(int x) {}
public void foo(String y) {}
public void foo(Object o) {}
public void foo() {}
foo(50); // Calls the first method
foo("hello"); // Calls the second method
// Calls the third method, because the compile-time type of the argument is
// Object, even though it's actually a reference to a string at execution time
foo((Object) "hello");
foo(); // Calls the fourth method
See more on this question at Stackoverflow