Java Reference
In-Depth Information
this
.name = name;
}
public
String getName ()
{
return
name ;
}
...
}
public class
Villain
{
private
String name;
private int
evilPower ;
private int
narcissism;
public void
setName( String name)
{
this
.name = name;
}
public
String getName ()
{
return
name ;
}
...
}
Note that the two classes share attributes and methods. They both have the
name
attribute and they both have the
setName
and
getName
methods. This is not a coincidence.
Both superheroes and villains are fictional characters and therefore they both
inherit
attributes and methods from the
FictionalCharacter
class. A better design is shown
next.
public class
FictionalCharacter
{
private
String name;
public void
setName( String name)
{
this
.name = name;
}
public
String getName ()
{
return
name ;
}
}
public class
Villain
extends
FictionalCharacter
{
private int
evilPower ;
private int
narcissism;
...
}
public class
Superhero
extends
FictionalCharacter
{
private int
goodPower ;
private int
respect ;
...
}
Now the classes
Villain
and
Superhero
inherit from the
FictionalCharacter
class.
Our design is shown in Figure 8.2. Such figures are sometimes referred to as UML dia-
grams, where UML stands for
Unified Modeling Language
. In a UML diagram, every class is
surrounded by a rectangle. The rectangle contains the class name, variables, and methods.
Arrows between classes are used to represent inheritance.