Java Reference
In-Depth Information
Self-Test Exercises
7. Would the following be legal for the definition of a method to add to the class
Employee (Display 7.2)? (Remember, the question is whether it is legal, not
whether it is sensible.)
public void crazyMethod()
{
Employee object = new Employee("Joe",
new Date("January", 1, 2005));
System.out.println("Hello " + object.name);
}
Would it be legal to add this crazyMethod to the class HourlyEmployee ?
8. Suppose you change the modifier before the instance variable name from private
to public in the class Employee . Would it then be legal to add the method
crazyMethod (from Exercise 7) to the class HourlyEmployee ?
PITFALL: Private Methods Are Effectively Not Inherited
As we noted in the previous Pitfall section: An instance variable (or method) that is
private in a base class is not directly accessible outside of the definition of the base
class , not even in a method definition for a derived class. The private methods of the
base class are just like private variables in terms of not being directly available. But
in the case of methods, the restriction is more dramatic. A private variable can be
accessed indirectly via an accessor or mutator method. A private method is simply
not available. It is just as if the private method were not inherited. (In one sense, pri-
vate methods in the base class may be indirectly available in the derived class. If a
private method is used in the definition of a public method of the base class, then
that public method can be invoked in the derived class, or any other class, so the pri-
vate method can be indirectly invoked.)
This should not be a problem. Private methods should just be used as helping meth-
ods, so their use should be limited to the class in which they are defined. If you want a
method to be used as a helping method in a number of inherited classes, then it is not
just a helping method, and you should make the method public.
Protected and Package Access
As you have seen, you cannot access (by name) a private instance variable or private
method of the base class within the definition of a derived class. There are two classifica-
tions of instance variables and methods that allow them to be accessed by name in a
derived class. The two classifications are protected access, which always gives access, and
package access, which gives access if the derived class is in the same package as the base class.
Search WWH ::




Custom Search