Static methods and their overriding
Java doesn't allow overriding of static methods but,
class stat13
{
static void show()
{
System.out.println("Static in base");
}
public static void main(Stri开发者_高级运维ng[] 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
Overriding happens when a child-class provides it's own implementation for a method such that the child-class instance will be invoked. The operative word here is - instance.
Static methods are invoked in the context of the class e.g.
stat13.show(...);
OR
next.show(...);
FWIW, your sample code is not an example of overriding.
Overriding happens at the object level. for ex obj1.overridedmenthod(). and there is no concept of overriding a class level method ie... static method ex : Class.overridedmethod().
and this concept of overriding a static method is named as method hiding.
try out a simple example .
精彩评论