Java Reference
In-Depth Information
}
}
public class Superhero extends FictionalCharacter
{
private int goodPower ;
private int respect ;
public Superhero(String name, int goodPower ,
int respect) {
super (name) ;
this . goodPower = goodPower ;
this . respect = respect ;
double computeStrength() {
return goodPower respect Math . random ( ) ;
} public String toString()
{
return super .getName()+ " is a superhero that has good power = " +
goodPower+ " and respect = " +respect ;
}
}
public class Villain extends FictionalCharacter
{
private int evilPower ;
private int narcissism;
public Villain(String name, int evilPower , int narcissism) {
super (name) ;
this . evilPower = evilPower ;
this . narcissism = narcissism;
double computeStrength() {
return evilPower narcissism Math . random ( ) 0.9;
} public String toString() {
return super .getName()+ " is a Villain that has evil power = " +
evilPower+ " and narcissism = " +narcissism;
}
}
Note that the three classes must be created in three separate files. As a general rule,
provide the weakest possible access privilege to each variable and method. In our example,
since the computeStrength method could not be defined as private , we defined it using
no modifier. If we put it inside a closed package, then nobody outside the package will be
able to access it.
Note that, so far, we have used either public or no modifier when defining classes.
Similar to variables and methods, a public class can be accessible from everywhere, while
a class with no modifier can only be accessible within the package. Remember that every file
must have exactly one public class that has the same name as the name of the file. A nested
class (i.e., a class within a class) can be defined as private ; more on this in Chapter 10.
 
Search WWH ::




Custom Search