More on Overriding
Changing Access Levels on Overridden Methods
You can change the access level of a method when you override it, but only
to make it more accessible.
- You can't restrict access any more than it was in the base class.
- So, for example, you could take a method that was
the base class and make it
- For example, if a method was
public in the base class, the
derived class may not override it with a method that has
This avoids a logical inconsistency:
- Since a base class variable can reference a derived class object, the compiler will allow it
to access something that was
public in the base class.
- If the derived class object actually referenced had changed the access level to
the element ought to be unavailable.
- This logic could be applied to any restriction in access level, not just
As a more specific example of why this is the case, imagine that
public String getPayInfo() with
private String getPayInfo().
The compiler would allow
Employee e = new ExemptEmployee();
// getPayInfo was public in Employee, so compiler should allow this
Employee, the type on the variable
e, says that
- But, now at runtime, it shouldn't be accessible, since it is supposed to
A field in a derived class may be redefined, with a different type and/or
more restrictive access - when you do this you are creating a second field
that hides the first; this is called shadowing instead of overriding.
- A new field is created that hides the existence of the original field.
- Since it actually a new field being created, the access level and even data type may be
whatever you want - they do not have to be the same as the original field.
- I don't know of any good reason to do this deliberately, but it is possible.
But, if you were to extend a class from the Java API or other library,
you wouldn't necessarily know what fields it had - this facility allows
you to use whatever field names you want, and, as long as the base class
- A strange thing happens when you use a base class reference to such a class where the field
was accessible (for example,
- The base class reference sees the base class version of the field!
private, you would not get any adverse effects.