Java Reference
In-Depth Information
TABLE 8 . 1 : Access privilege modifiers.
Modifier Accessible from
public everywhere
protected same package and subclasses
no modifier only within same package
only from same class
to the rest of the world. However, the computeStrength method is still defined as public
and anyone can call it. The astute reader may suggest that we can simply define the method
as private . However, this is impossible in this case. The reasons are that (1) an abstract
method cannot be defined as private and (2) a private method cannot be overridden.
Before we present the solution to the problem, let us first examine the possible modi-
fiers for access privileges in Java. Table 8.1 shows them in tabular format. The protected
keyword means that the data or method is accessible within the same package and within
the subclasses. No modifier is when no access privileges are specified. In this case, the class
member is accessible only within the package.
When overriding a method in a subclass, Java does not allow us to assign weaker
access privileges. For example, a protected method cannot be overridden as private .
It can only be overridden as protected ,nomodifier,or public .
Note that a private method cannot be overridden. The reason is that the subclass should
not know about the existence of a private method in the superclass. Note that we cannot
define the computeStrength method in the FictionalCharacter class as private .The
reason is that we will not be able to override it in the subclasses. Our next choice is to
define it using no modifier. Here is the refactored code that shows a better design.
public abstract class FictionalCharacter implements Comparable <
FictionalCharacter >{
private String name;
public FictionalCharacter () {
} public FictionalCharacter(String name) {
this .name = name;
public String getName ()
return name ;
} public void setName( String name) {
this .name = name;
abstract double computeStrength() ;
public int compareTo(FictionalCharacter other) {
if (computeStrength() other . computeStrength() > 0) {
return 1;
} if (computeStrength() other . computeStrength() < 0) {
return 1;
return 0;
Search WWH ::

Custom Search