Java Reference
In-Depth Information
For example, suppose one class definition includes the following details:
public class BaseClass
{
...
public Employee getSomeone( int someKey)
...
In this case, the following details would be allowed in a derived class:
public class DerivedClass extends BaseClass
{
...
public HourlyEmployee getSomeone( int someKey)
...
When the method definition for getSomeone is overridden in DerivedClass , the
returned type is changed from Employee to HourlyEmployee .
It is worth noting that when you change the returned type of an overridden
method in this way, such as from Employee to HourlyEmployee , you are not really
changing the returned type so much as placing additional restrictions on it. Every
HourlyEmployee is an Employee with some additional properties that, while they are
properties of every HourlyEmployee , are not properties of every Employee . Any code
that was written for a method of the base class and that assumed the value returned
by the method is Employee will be legal for an overridden version of the method
that returns an HourlyEmployee . This is true because every HourlyEmployee is an
Employee .
Changing the Access Permission of an Overridden Method
You can change the access permission of an overridden method from private in
the base class to public in the derived class (or in any other way that makes access
permissions more permissive). For example, if the following is a method heading in a
base case,
private void doSomething()
then you can use the following heading when overriding the method definition in a
derived class:
public void doSomething()
Note that you cannot change permissions to make them more restricted in the
derived class. You can change private to public , but you cannot change public to
private .
 
Search WWH ::




Custom Search