Reputation: 2920
It is written everywhere that static method cannot be overriden, but when I try to reduce the access specifier say from public to protected it gives an error. for example
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 the inherited method
So insense it is following the overriding rules, how come we are saying foo is not being overridden in B class? Why do we say it is hiding/shadowing and not overriding?
Upvotes: 3
Views: 467
Reputation: 2762
You yourself posted answer in your question, overriding means having different code in child class for same method. As static methods cannot be overridden you cannot play with the visibility by modifying access specifiers.
Upvotes: -1
Reputation: 1500525
It's following some of the same rules as overriding, but that doesn't mean it is overriding. In this case, it's the rules in section 8.4.8.3 of the JLS, "Requirements in Overriding and Hiding":
The access modifier (§6.6) of an overriding or hiding method must provide at least as much access as the overridden or hidden method, as follows: [...]
It's still not overriding, as the method wouldn't be invoked polymorphically - you can't write a call which will sometimes end up calling StaticOverrideFunda.foo
and sometimes end up calling B.foo
; the target is determined entirely at compile time.
It would be worth reviewing the rest of section 8.4.8, which defines overriding as being something which occurs on instance methods.
Upvotes: 8