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";
}
}
A static method has two main purposes: For utility or helper methods that don't require any object state. Since there is no need to access instance variables, having static methods eliminates the need for the caller to instantiate the object just to call the method.
A static method (or static function) is a method defined as a member of an object but is accessible directly from an API object's constructor, rather than from an object instance created via the constructor.
Static methods are often utility functions, such as functions to create or clone objects, whereas static properties are useful for caches, fixed-configuration, or any other data you don't need to be replicated across instances.
Types of Java Static Members The static field(static variables) and static method are the two types of static members in java. Let's discuss each member one by one.
You cannot override static methods in Java. It's simply calling the static methods directly on each class. BTW: As others have noted, it's considered bad practice to call static methods on instances. For clarity, you should do the following:
System.out.println(Tenor.sing() + " " + Singer.sing());
which is equivalent to the code you have written in your question.
Static methods should be accessed with the class name and not an object reference. The correct equivalent of what you wrote would be:
System.out.println(Tenor.sing() + " " + Singer.sing())
Java is guessing inferring which method you meant to invoke based on the type of object variable.
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:
Singer s = new Tenor();
System.out.println(s.sing());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With