I am new to Java Programming. Can anyone please explain me why the program outputs – “fa la” even though the static method is overridden. I read that static methods can’t be overridden in Java? Please correct me if I am wrong.
public class Tenor extends Singer {
public static String sing() {
return "fa";
}
public static void main(String[] args) {
Tenor t = new Tenor();
Singer s = new Tenor();
System.out.println(t.sing() + " " + s.sing());
}
}
class Singer {
public static String sing() {
return "la";
}
}
Static methods should be accessed with the class name and not an object reference. The correct equivalent of what you wrote would be:
Java is
guessinginferring which method you meant to invoke based on the type ofobjectvariable.EDIT: As Stephen pointed out, it isn’t guessing. Inferring would probably be a more accurate word. I was just trying to emphasize that calling static functions on object references might result in behavior you wouldn’t expect. In fact, I just tried a few things and found out that my previous statement was incorrect: Java decides which method to call based on the variable type. This is obvious now that I think about it more but I can see how it could lead to confusion if you did something like: