Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java non-static to static method -- hiding or overriding

is re-defining a non-static method in a subclass with the same everything but as static overriding or hiding it ?

http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html says hiding. but when i declare the superclass method as final, i get an override error.

superclass declaration is

final static void display() { ... }

subclass:

void display() { ... }

gives override error.

like image 543
ashley Avatar asked Oct 20 '25 08:10

ashley


1 Answers

Is re-defining a non-static method in a subclass with the same everything but as static overriding or hiding it?

It's neither, because doing so triggers a compilation error, rendering your program invalid.

class A {
    void x();
}
class B extends A {
    // ERROR!!!
    static void x();
}

Hiding happens when both methods in the pair are static methods; overriding happens when both methods in the pair are instance methods. When one of the two is a static method and the other one is an instance method, Java considers it an error. It does not matter if the instance method is final or not; it also does not matter if the static method is in the base or in the derived class: Java calls it an error either way.

The compiler message that says "cannot override" is misleading, though: I think that "name collision" would have been a better name for such conditions, because "overriding" is reserved for situations with two instance methods.

like image 185
Sergey Kalinichenko Avatar answered Oct 22 '25 23:10

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!