Static Methods in Java

I am new to Java programming. Can someone explain to me why the program outputs - "fa la", even if the static method is overridden. I read that static methods cannot 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"; } } 
+7
source share
6 answers

Static methods should be available with the class name, not an object reference. The correct equivalent of what you wrote:

 System.out.println(Tenor.sing() + " " + Singer.sing()) 

Java is to guess the conclusion about which method you should call based on type object .

EDIT: As Stephen remarked, this is not a guess. The conclusion is likely to be a more accurate word. I was just trying to emphasize that calling static functions in object references can lead to behavior you don't expect. In fact, I just tried a few things and found out that my previous statement was wrong: Java decides which method to call based on the type of the variable. This is obvious now, when I think about it more, but I see how this can lead to confusion if you did something like:

 Singer s = new Tenor(); System.out.println(s.sing()); 
+4
source

You cannot override static methods in Java. It simply calls static methods directly for each class. By the way: as others have noted, he believed that bad practice calls static methods for instances. For clarity, you should do the following:

 System.out.println(Tenor.sing() + " " + Singer.sing()); 

which is equivalent to the code you wrote in your question.

+12
source

t is of type Tenor and s is of type Singer .

When you call a static instance method (which is bad practice), you call a static method in a class of the declared type.

i.e. t.sing() equivalent to Tenor.sing()

+4
source

Static methods are not overridden. They belong to the class in which they are defined. Calling a static method on an instance of this method works the same way as calling it in a class, but makes it less understandable and leads to people thinking that they are overridden as instance methods.

+2
source

Static methods cannot be overridden.

The following resource will help you better understand what happens when you try to override a static method:

http://www.javabeat.net/qna/49-can-we-override-static-methods-what-is-metho/

Regards, Cyril

+2
source

The code you wrote works fine, but probably not the way you intended it. Static methods cannot be redefined in the traditional sense (or with the behavior you might expect). In terms of which version of the method is invoked, this is done at compile time , which explains the output you see.

Yes, and you should probably only call methods using the class name.

0
source

All Articles