Overriding a method with a weaker access-modifier is prohibited by the standard (§8.4.8.3):
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:
If the overridden or hidden method is public, then the overriding or hiding method must be public; otherwise, a compile-time error occurs.
If the overridden or hidden method is protected, then the overriding or hiding method must be protected or public; otherwise, a compile-time error occurs.
If the overridden or hidden method has default (package) access, then the overriding or hiding method must not be private; otherwise, a compile-time error occurs.
This ensures that any method provided by the base-class can also be called on derived classes within the same context.
Variables can't be overriden. Base.className
and Derived.className
are two distinct variables. Thus it is perfectly valid to have a variable with the same name and different access-modifier in Derived
.
I.e. this code will print false
:
class Base{
public String str = "hello";
}
class Derived extends Base{
private String str = "whatever";
public Derived(){
super.str = "abc";
str = "def";
}
void foo(){
System.out.println(str.equals(super.str));
}
}
public static void main(String[] args){
new Derived().foo();
}
The relevant jls-sections:
Field declarations (§8.3):
The scope and shadowing of a field declaration is specified in §6.3 and §6.4.
If the class declares a field with a certain name, then the declaration of that field is said to hide any and all accessible declarations of fields with the same name in superclasses, and superinterfaces of the class.
In this respect, hiding of fields differs from hiding of methods (§8.4.8.3), for there is no distinction drawn between static and non-static fields in field hiding whereas a distinction is drawn between static and non-static methods in method hiding.
A hidden field can be accessed by using a qualified name (§6.5.6.2) if it is static, or by using a field access expression that contains the keyword super (§15.11.2) or a cast to a superclass type.
In this respect, hiding of fields is similar to hiding of methods.
If a field declaration hides the declaration of another field, the two fields need not have the same type.
And Shadowing (§6.4.1):
A declaration d of a field or formal parameter named n shadows, throughout the scope of d, the declarations of any other variables named n that are in scope at the point where d occurs.