Strange case of overriding a static method in java

Everywhere they write that the static method cannot be overridden, but when I try to reduce the access specifier, from open to protected, it gives an error. eg

public class StaticOverrideFunda { public static void foo(){ System.out.println("Parent Foo"); } } public class B extends StaticOverrideFunda{ protected static void foo(){ System.out.println("Child Foo"); } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub B.foo(); } } 

It says

Cannot reduce the visibility of a legacy method

So it depends on the basic rules, why do we say that foo is not overridden in class B? Why are we saying this is hiding / shading and not overriding?

+3
source share
2 answers

It follows some of the same rules as redefinition, but that does not mean that it redefines. In this case, these are the rules in the section of 8.4.8.3 JLS , "Requirements for Overriding and Hiding":

The access modifier (ยง6.6) of the override or hide method must provide at least the same access as the overridden or hidden method, as follows: [...]

It still does not override, since the method will not be called polymorphically - you cannot write a call that sometimes ends with a call to StaticOverrideFunda.foo , and sometimes calls B.foo ; the target is fully determined at compile time.

It would be useful to consider the rest of section 8.4.8, which defines overriding as something that happens in instance methods.

+8
source

You yourself posted the answer in your question, overriding a tool that has different code in the child class for the same method. Because static methods cannot be overridden, you cannot play with visibility by changing access specifiers.

-1
source

Source: https://habr.com/ru/post/1238696/


All Articles