Java Reference
In-Depth Information
value = 3
value = 5
dice array
value = 2
DiceCup object
FIGURE 8.1: Object composition.
DiceCup contains three dice with values: 3, 5, and 2. Note that it is possible that memory
for the array has not been allocated, that is, a DiceCup object may contain no dice.
Class composition is sometimes referred to as the has relationship. For example, a
DiceCup has Die objects. Class composition is implemented by defining a variable of
one type inside a class of a different type.
An object that contains other objects is sometimes referred to as a composite object .As
we will see later in this chapter, special care needs to be taken when copying composite
objects. Not only the data inside the object, but also all the objects inside it need to be
copied.
8.2 Inheritance and the super Keyword
Let us consider a game of villains and superheroes. The player can create villains and
superheroes. For villains, the player needs to specify the name of the villain and the strength
of their evil power and narcissism. For superheroes, the player needs to specify how much
they are respected and the strength of their good powers. All strengths will be represented
as an integer between 1 and 10. The program will make the fictional characters fight each
other and report the results. A possible design of the two classes is shown next.
public class Superhero
{
private String name;
private int goodPower ;
private int respect ;
public void setName( String name) {
 
Search WWH ::




Custom Search