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?
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.
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.
Java does not give compiler error for this. but this method will not behave like what you expect it to... better explained here
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