Yes.
class Video
{
private String title; // name of the item
private int length; // number of minutes
private boolean avail; // is the video in the store?
// constructor
public Video( String ttl )
{
title = ttl; length = 90; avail = true;
}
// constructor
public Video( String ttl, int lngth )
{
title = ttl; length = lngth; avail = true;
}
. . .
}
class Movie extends Video
{
private String director; // name of the director
private String rating; // G, PG, R, or X
// constructor
public Movie( String ttl, int lngth, String dir, String rtng )
{
super(ttl, lngth); // use the base class's constructor to initialize members inherited from it
director = dir; // initialize the members new to Movie
rating = rtng;
}
. . .
}
Look at the constructor for class Movie.
The class definition for Video has a constructor that
initializes the instance variables of Video objects.
The class Movie has a constructor that initializes the instance variables of
Movie objects.
The statement super(ttl, lngth)
invokes a
constructor of the parent
to initialize some variables of the child.
There are two constructors in the parent.
The one that is invoked is the one that matches the argument list
in super(ttl, lngth).
The next two statements initialize
variables that only Movie has.
Important Note:
super()
must be the first statement
in the subclass's constructor.
This fact is often overlooked and may cause mysterious compiler error messages.
| member | where defined | how initialized |
|---|---|---|
| title | inherited from Video | super(ttl, lngth); |
| length | inherited from Video | super(ttl, lngth); |
| avail | inherited from Video | super(ttl, lngth); |
| director | defined in Movie | director = dir; |
| rating | defined in Movie | rating = rtng; |
Why is the statement that
invokes the parent's constructor called super()?