Java Reference
In-Depth Information
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;
}
public static int
memberCount ()
{
return
memberCount ;
}
}
The static variable
memberCount
keeps track of the number of fictional characters. The
count is initially zero and is incremented by one every time a new fictional character is
created. The variable is
static
because it is not associated with a particular object, but
rather with the whole class. Next, imagine we also add object counting capabilities to the
Superhero
class.
public class
Superhero
extends
FictionalCharacter
{
private int
goodPower ;
private int
respect ;
private static int
memberCount = 0;
public
Superhero
{
memberCount++;
}
public
Superhero(String name,
int
goodPower ,
int
respect)
{
super
(name) ;
this
. goodPower = goodPower ;
this
. respect = respect ;
memberCount++;
double
{
return
goodPower
∗
respect
∗
Math . random ( ) ;
}
public
String toString()
{
return super
.getName()+
" is a superhero that has good power = "
+
goodPower+
" and respect = "
+respect ;
}
public static int
memberCount ()
{
return
memberCount ;
computeStrength()
}
}
Now, if we call
Superhero.memberCount()
,thenwewillgetthenumberofsuperheroes.
Conversely, the code
FictionalCharacter.memberCount()
will return the number of fic-
tional characters. Note that if the
memberCount
method for the
Superhero
classisre-