More on Overriding

Welcome to our free Java tutorial. This tutorial is based on Webucator's Introduction to Java Training course.

Contact Us or call 1-877-932-8228
More on Overriding

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 protected in the base class and make it public.
  • For example, if a method was public in the base class, the derived class may not override it with a method that has protected, private or package access.

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 private, then the element ought to be unavailable.
  • This logic could be applied to any restriction in access level, not just public to private.

As a more specific example of why this is the case, imagine that ExemptEmployee overrode 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
e.getPayInfo();
  • Because Employee, the type on the variable e, says that getPayInfo is public.
  • But, now at runtime, it shouldn't be accessible, since it is supposed to be private in ExemptEmployee.

Redefining Fields

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.
    • A strange thing happens when you use a base class reference to such a class where the field was accessible (for example, public).
    • The base class reference sees the base class version of the field!
    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 versions were private, you would not get any adverse effects.
Next

This tutorial is based on Webucator's Introduction to Java Training Course. We also offer many other Java Fundamentals Training courses. Sign up today to get help from a live instructor.