[Logo]
Forums Register Login
static methods

i read many times that static methods cannot be overridden but in the code above when i try to write the "message()" method in StaticChild without static keyword class I get an error "overridden method is static". when i tried to compile the code putting static modifier before message() in the class StaticChild i get an error "Attempting to assign weaker privileges". Now if the static methods cannot be overridden and two Static method in class hierarchy means two independent class methods why do i have to declare "message()", in StaticChild class, with protected or public specifier if its not overriding "message()" in StaticParent class. it seems to me that it is simply following the criteria for overriding a method but it wasn't supposed to because static methods cannot be overridden. i m so confused
Welcome to Coderanch, Madhurendra Narayan Tiwary.

Madhurendra Narayan Tiwary wrote:

i read many times that static methods cannot be overridden but in the code above when i try to write the "message()" method in StaticChild without static keyword class I get an error "overridden method is static".



In Java, instance methods cannot override static methods. I suggest you read this.

Madhurendra Narayan Tiwary wrote:
when i tried to compile the code putting static modifier before message() in the class StaticChild i get an error "Attempting to assign weaker privileges".



That is one of the general method overriding rules . If you think of it, it would make the method application inconsistent if subclasses were allowed to reduce an inherited method's visibility.

Madhurendra Narayan Tiwary wrote:
Now if the static methods cannot be overridden and two Static method in class hierarchy means two independent class methods why do i have to declare "message()", in StaticChild class, with protected or public specifier if its not overriding "message()" in StaticParent class. it seems to me that it is simply following the criteria for overriding a method but it wasn't supposed to because static methods cannot be overridden. i m so confused



In case of static methods, since it is redefinition not overridding, there is no run time polymorphism into play. And static methods are not associated with an object. So we only need the class name to invoke them. If redefinitions of the kind that restricted a method's visibility were allowed, and if you invoked such a static subclass method, you couldn't be sure which part of your code would invoke the superclass method and which part would invoke the subclass method. Remember static methods are not overridden, but they are inherited.

With the way it stands now, if you invoked <Subclass>.<static method>(), it's either the super class method, or it's the subclass method that would be called consistently in all the places.
thank you

This thread has been viewed 545 times.

All times above are in ranch (not your local) time.
The current ranch time is
Sep 25, 2018 07:30:12.