Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static methods and their overriding

Tags:

java

Java doesn't allow overriding of static methods but,

class stat13
{
    static void show()
    {
        System.out.println("Static in base");
    }
    public static void main(String[] ar)
    {
        new next().show();
    }
}


class next extends stat13
{
    static void show()
    {
        System.out.println("Static in derived");
    }
}

is not overriding done here?

like image 376
abson Avatar asked Mar 26 '10 06:03

abson


3 Answers

No, you're not overriding anything - you're just hiding the original method.

It's unfortunate that Java allows you to call a static method via a reference. Your call it more simply written as:

next.show();

Importantly, this code would still call the original version in stat13:

public static void showStat(stat13 x)
{
    x.show();
}
...
showStat(new next());

In other words, the binding to the right method is done at compile-time, and has nothing to do with the value of x - which it would normally with overriding.

like image 78
Jon Skeet Avatar answered Sep 28 '22 13:09

Jon Skeet


This is "hiding", not "overriding". To see this, change the main method to the following:

public static void main (String[] arghh) {
    next n = new next();
    n.show();
    stat13 s = n;
    s.show();
}

This should print:

Static in derived
Static in base

If there was real overriding going on, then you would see:

Static in derived
Static in derived

It is generally thought to be bad style to invoke a static method using an instance type ... like you are doing ... because it is easy to think you are invoking an instance method, and get confused into thinking that overriding is happening. A Java style checker / code audit tool will typically flag this as a style error / potential bug.

like image 43
Stephen C Avatar answered Sep 28 '22 14:09

Stephen C


Java does not give compiler error for this. but this method will not behave like what you expect it to... better explained here

like image 38
RubyDubee Avatar answered Sep 28 '22 13:09

RubyDubee