Professional Documents
Culture Documents
Exercise: Inheritance
1. Here is a program that uses a class Video to represent videos available at a rental
store. Try to trace out what will this program print.
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;
}
item1.show();
item2.show();
}
}
2. Now copy this program, save it, compile and run it. See if the output matches yours in
step 1.
1
____________________________________________________________________
_
STIA1123___________________________________________________________________________________
3. Let’s make a Movie class that is similar to Video, but also includes the name of the
director and a rating. The class is given as follows:
// constructor
public Movie( String ttl, int lngth, String dir, String rtng )
{
super( ttl, lngth ); //use the super class's constructor
director = dir; rating = rtng;
}
4. The class Movie is a subclass of Video. List all of the members of a Movie object and
for each member state whether it is inherited from Video or defined in Movie.
2
____________________________________________________________________
_
STIA1123___________________________________________________________________________________
6. To print out all data members of a Movie object, we need to override the show()
method that is inherited from Video. Change the definition of the Movie class to
override the parent’s show() method:
7. Now compile and run again the VideoStore program given in step 5. This time what
does the program print?
8. Overload the Movie constructor by adding the following constructor definition in the
Movieclass and recompile the class (Make sure there is no error).
super( ttl );
in the above constructor. Now compile the class and you’ll get a compilation error.
Explain why? Then make the correction for the error.
3
____________________________________________________________________
_