Java Reference
In-Depth Information
this .name = name;
}
}
Next, let us explore the Superhero class and its constructors. When creating a
Superhero object, we also need to create a FictionalCharacter object. Therefore, in the
first line of every constructor of the Superhero class, we must create a FictionalCharacter
super object. If such an object is not explicitly created, then the empty constructor for the
FictionalCharacter class is explicitly called. Here is one possible implementation of the
non-empty constructor for the Superhero class.
public class Superhero extends FictionalCharacter
{
private int goodPower ;
private int respect ;
public Superhero(String name, int goodPower ,
int respect)
{
this . goodPower = goodPower ;
this . respect = respect ;
super . setName(name) ;
}
}
In the above code, a call that creates the super object is not present. Therefore, the
empty constructor is called to create the super object. In the last line, the name for the
super object is changed using the setName method. This design looks clumsy. Alternatively,
we can explicitly create the super object as shown next.
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 ;
}
}
The statement super(name) creates the super object. Note that this statement must
be the first statement of the constructor. This command calls a constructor of the
FictionalCharacter class (i.e., the superclass). The call to the constructor is used to
create the super object.
The empty constructor for the Superhero class can be created as follows.
class Superhero extends FictionalCharacter
{
class Superhero() {
} ...
}
We can add super() to the first line of the constructor. However, this is not necessary.
The reason is that the empty constructor of the superclass is called if the super keyword is
not used to call it in the first line of the method. If the superclass does not have an empty
constructor, then a syntax error is generated. The above code is equivalent to the following
code.
class Superhero extends FictionalCharacter {
class Superhero() {
super () ;
 
Search WWH ::




Custom Search