142

I have been playing around with modifiers with static method and came across a weird behaviour.

As we know, static methods cannot be overridden, as they are associated with class rather than instance.

So if I have the below snippet, it compiles fine

//Snippet 1 - Compiles fine
public class A {
    static void ts() {
    }
}

class B extends A {
    static void ts() {
    }
}

But if I include final modifier to static method in class A, then compilation fails ts() in B cannot override ts() in A; overridden method is static final.

Why is this happening when static method cannot be overridden at all?

aioobe
  • 413,195
  • 112
  • 811
  • 826
Harish
  • 7,589
  • 10
  • 36
  • 47

8 Answers8

189

Static methods cannot be overridden but they can be hidden. The ts() method of B is not overriding(not subject to polymorphism) the ts() of A but it will hide it. If you call ts() in B (NOT A.ts() or B.ts() ... just ts()), the one of B will be called and not A. Since this is not subjected to polymorphism, the call ts() in A will never be redirected to the one in B.

The keyword final will disable the method from being hidden. So they cannot be hidden and an attempt to do so will result in a compiler error.

starball
  • 20,030
  • 7
  • 43
  • 238
NawaMan
  • 25,129
  • 10
  • 51
  • 77
  • 35
    To perhaps finish your answer, which is right I believe, the problem here is basically a bad compiler error message: it should says B cannot *hide* ts() in A. Declaring a static method final is declaring it cannot be hidden. – Sean Owen Nov 16 '09 at 17:58
  • 2
    @Sean Owen: I think so too. The term 'hide' is even used in Java Specification so why not use it in the compiler message. – NawaMan Nov 16 '09 at 18:10
  • 4
    Why is this even a feature? In what context would it be useful? – user253751 Mar 25 '15 at 04:32
  • public class Test { final static public void main(String... srik) { System.out.println("In main method"); ts(); } public static void ts() { Child c=new Child(); c.ts(); System.out.println("Test ts"); } } public class Child extends Test { public static void ts() { System.out.println("Child ts"); } } Hi Can u plz explain me what happens in this scenario – srikanth r Feb 20 '16 at 11:14
  • @SeanOwen I don't think this is correct either, the compiler should say that since `A#ts` is being inherited and such a method already exists in `B`, simply having two methods with the same signature and a different modifier (`final`) would not work as overloads... I wish I could think of a simple message for this, though – Eugene Apr 10 '18 at 11:36
  • 1
    My book "java how to program edition 10" says static methods are implicitly final (chapter 10.7). http://prntscr.com/u3too3 If static methods are final, and if final methods cant be hidden. That means static methods shouldn't be hidden aswell. But we are able to hide static methods. – Michael Aug 22 '20 at 02:38
16

static methods cannot be overriden

This is not exactly true. The example code really means that the method ts in B hides the method ts in A. So its not exactly overriding. Over on Javaranch there is a nice explanation.

MC Emperor
  • 22,334
  • 15
  • 80
  • 130
Vincent Ramdhanie
  • 102,349
  • 23
  • 137
  • 192
  • 5
    It is true just not precise. static methods cannot be overridden but can be hidden if you are calling them on a instance reference rather than the class name. – John Mercier Feb 26 '15 at 15:09
  • 1
    Unfortunately your link isn't working any more. Is it possible to fix this? – Mathias Bader Sep 12 '17 at 11:54
  • The javaranch link isn't working, but Googling the key words turned up [this link](https://coderanch.com/wiki/659959/Overriding-Hiding) on code ranch – Sundeep Nov 28 '18 at 14:34
  • I've edited the post by replacing the dead link by the link posted by Sundeep. – MC Emperor May 17 '19 at 11:54
12

Static methods belong to the class, not the instance.

A.ts() and B.ts() are always going to be separate methods.

The real problem is that Java lets you call static methods on an instance object. Static methods with the same signature from the parent class are hidden when called from an instance of the subclass. However, you can't override/hide final methods.

You would think the error message would use the word hidden instead of overridden...

Powerlord
  • 87,612
  • 17
  • 125
  • 175
10

You might find yourself in the position to think about making a static method final, considering the following:

Having the following classes:

class A {
    static void ts() {
        System.out.print("A");
    }
}
class B extends A {
    static void ts() {
        System.out.print("B");
    }
}

Now the 'correct' way to call these methods would be

A.ts();
B.ts();

which would result in AB but you could also call the methods on instances:

A a = new A();
a.ts();
B b = new B();
b.ts();

which would result in AB as well.

Now consider the following:

A a = new B();
a.ts();

that would print A. That might surprise you since you are actually having an object of class B. But since you're calling it from a reference of type A, it will call A.ts(). You could print B with the following code:

A a = new B();
((B)a).ts();

In both cases the object you have is actually from class B. But depending on the pointer that points to the object, you will call method from A or from B.

Now let's say you are the developer of class A and you want to allow sub-classing. But you really want method ts(), whenever called, even from a subclass, that is does what you want it to do and not to be hidden by a subclass version. Then you could make it final and prevent it from being hidden in the subclass. And you can be sure that the following code will call the method from your class A:

B b = new B();
b.ts();

Ok, admittetly that is somehow constructed, but it might make sense for some cases.

You should not call static methods on instances but directly on the classes - then you won't have that problem. Also IntelliJ IDEA for example will show you a warning, if you call a static method on an instance and as well if you make a static method final.

Ahmed Mourad
  • 193
  • 1
  • 2
  • 18
Mathias Bader
  • 3,585
  • 7
  • 39
  • 61
0

The ts() method in B is not overriding the ts() method in A, it simply is another method. The B class does not see the ts() method in A since it is static, therefore it can declare its own method called ts().

However, if the method is final, then the compiler will pick up that there is a ts() method in A that should not be overridden in B.

amischiefr
  • 4,750
  • 2
  • 29
  • 22
  • I don't think this explains why 'final' suddenly means these methods can't coexist. As you say, without 'final', there's no problem. You say it's not overriding, but then say the problem is that B can't override A's method. – Sean Owen Nov 16 '09 at 17:55
  • Sure it does, I state that B does not see the method ts() in A (it is 'hidden'), but the final modifier does not 'hide' methods from classes that extend another one. But eh, ok. – amischiefr Nov 16 '09 at 18:03
  • I think perhaps your phrasing "should not be overridden in B" could be changed to "should not be hidden in B" – Scratte Sep 17 '20 at 10:02
0

I think the compilation error was quite misleading here. It should not have said "overridden method is static final.", but it should instead have said "overridden method is final.". The static modifier is irrelevant here.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 1
    So you consider the static method in B overriding the one in A? – Koray Tugay Jun 24 '17 at 10:07
  • @KorayTugay I just wonder if the compiler first looks at the *potentially* overridable method (ignores static for a moment), sees final at fails. Just a wild guess though – Eugene Apr 30 '18 at 11:48
  • Balus I think this is the only low quality answer you have in StackOverflow. Considering all your exceptional answers, this one does not belong to them. @BalusC – Koray Tugay Apr 30 '18 at 12:14
  • @KorayTugay: at that time I didn't had enough reputation to comment :) If you ping back, I'll delete the answer, no problem. – BalusC May 13 '18 at 08:35
0

A static method can't be overridden in Java, unlike non-static methods. But they are inherited like static and non-static data members. That is why a non-static method with the same name can't be created in the parent class

class Writer { 
    public static void doo(){
        System.out.println("sth");
    } 
}
class Author extends Writer{ 
    public void doo(){
        System.out.println("ok"); // error overridden method is static
    }
}

The final keyword ensures that the specific method body be run everytime a call to the method. Now if a static method is created in the child class with the same name and a call to the method is made, the method in the subclass gets executed which should not be the case if final is prefixed before the static method name in the parent class. Hence final keyword restricts the creation of method with the same name in the child class.

Pratik Gupta
  • 63
  • 1
  • 5
  • "But they are inherited like static and non-static data members." I do not think so. They are *accessible* from the child class, but that is not the same as inherited. "final keyword restricts the creation of method with the same name in the child class." is also not correct. You can overload a static final method in a child class. You just can't create a method with the same signature. – Scratte Sep 17 '20 at 09:56
0

Static methods are "hidden" in inherited classes and cannot be overridden "non-statically" i.e. they cannot be overridden in a "polymorphism" sense. But they can be overridden "statically".

Static final methods are not allowed to be overridden even "statically".

The following example illustrates this -

App.java -

public class App {
    public static void main(String[] args) {
        Base.fun1();
        Base.fun2();
        Derived1.fun1();
        Derived1.fun2();
        Derived2.fun1();
        Derived2.fun2();
    }
}

Base.java -

public abstract class Base {

    protected static void fun1() {
        System.out.println("Static fun1() called in Base");
    }

    protected static final void fun2() {
        System.out.println("Static final fun2() called in Base");
    }

}

Derived1.java -

public class Derived1 extends Base {

    protected static void fun1() {
        System.out.println("Static fun1() called in Derived1");
    }
    
    //Not allowed to override final method
    /*
    protected static final void fun2() {
        System.out.println("Static final fun2() called in Derived1");
    }
    */
}

Derived2.java -

public class Derived2 extends Base {

    protected static void fun1() {
        System.out.println("Static fun1() called in Derived2");
    }
    
    //Not allowed to override final method
    /*
    protected static final void fun2() {
        System.out.println("Static final fun2() called in Derived2");
    }
    */
}

Output -

Static fun1() called in Base
Static final fun2() called in Base
Static fun1() called in Derived1
Static final fun2() called in Base
Static fun1() called in Derived2
Static final fun2() called in Base
Payel Senapati
  • 1,134
  • 1
  • 11
  • 27