Inheritance in Java

Introduction

This resource can be used as an introduction to inheritance in Java. It will include It is assumed that you have some basic knowledge of Java. You should be familiar with the concept of an object and how to call methods.

This symbol indicates something that can be used either on the computer as practice or as an assignment.

This symbol indicates something that can be used either as a homework exercise or test question.

It is best not to print this page. The applets will either not show up or mess up the printing, depending on what browser you are using. The class listings that you can pop up from the applets also can't be printed from the windows. You can get a printable version of this web page and can download the classes. All the Java classes used in this resource are found there. You can download any that you want.

Why Use Inheritance

Inheritance is a large part of the reason that Object Oriented Programming is a powerful tool. It has the following advantages:

Terminology

There are a number of terms that you need to know to follow the examples:

field a variable that is part of a class
method a function that is part of a class
constructor a special method that is called when an object is created
superclass the class that is inherited from (the parent class)
subclass the class the does the inheriting (the child class)
extends in Java the keyword extends means that a class will inherit from another class
overload a method is overloaded if there are two or more methods with the same name in a class. Each overloaded method has a different set of parameters. That's how you can tell which one will get called.
override a method is overridden if there is a method in the subclass that has the same name and the same set of parameters. The superclass method is then NOT inherited.



Here is a class that might help illustrate some of these terms. Suppose you wanted a class that would allow you to use fractions in a program. This is the beginning of a class to do that. If your were going to actually use a class like this you'd want to add a lot more methods such as ones to reduce fractions to lowest terms and do other arithmetic operations. But this is enough to explain things. Move the mouse around in the code below to see the terms explained.


Here is a class that inherits from the Fraction class.


If you click the button labelled See class WITHOUT inheritance you can see how much more work would be required without inheritance. And in most situations the amount of savings in reuse of code is much more pronounced than this.

Vehicle Example

Before we go any farther let's take a look at an example. Suppose we were going to create a program that draws different kinds of vehicles. Each vehicle will look different. For example, we could have cars and boats. But all our vehicles will share many things in common. Here is a list of those things: So we'll start off by creating the superclass that does all those things. We'll call this class Vehicle. All our other types of vehicles will be subclasses of this. That way we won't have to rewrite any of the code that will be the same for all the classes. This is because the subclasses will inherit the methods of the superclasses.

When you move the cursor into these applets you'll notice the pointer turns into a hand. This is to let you know that each time you press the mouse button on the white part of the applet you'll go to the next step in the example.


A Car has all the same features as a Vehicle. The only difference is that the Car is drawn with wheels at the bottom. By using inheritance we can take advantage of the work that we've already done with the Vehicle. The Car class will be much smaller. In the same way we can create another class that extends Vehicle. We'll call this class Boat.


1

Create an applet that displays a blue Car near the left edge of the applet. Change the size of the car to 100 x 50. Display a pink Boat near the right edge of the applet.

Hint: If you are unfamiliar with using Applets here is a template you can use to help you get started.


We can also extend a subclass. We will make a class called Ferry which extends Car. It inherits not only the features of Car but also those of Vehicle. It looks like a Car with a Boat on the bottom. The following applet illustrates the inheritance hierarchy we have created.


You can see the full code for any of the above applets (actually for all the Java code in this resource). Take a look if you want to see how the Buttons and mouse clicks and so on are handled.

An Aside

Don't Panic if this doesn't make sense.
If you've been looking at the source code in the previous examples you may have wondered at some strange symbols appearing in the comments in the listing. In some places in the comments you will see some HTML tags. In others you will see the @ symbol. These symbols are used by a program that comes with Sun's Java package. The program is called javadoc. It makes nice external documentation in HTML format. It helps to illustrate inheritance heirarchies and what exactly gets inherited and from where. I've used it for several of my classes. Check out the javadocs for this resource. Sun provides documentation like this for the whole language. I find the more Java I learn the more I depend on their documentation to see what methods are available and how to use them. It's on the net at the Java website. You can download this information to use offline at Franck Allimant's website. This is not as necessary as it once was but sometimes it is nice to have the info offline (and may also be quicker to find the class you want.

2

Create an applet that displays an orange Ferry near the middle of the applet. Place two buttons in the applet. The buttons will say Larger and Smaller. If the user clicks on the larger button increase the ferry's width and height by 5. If the user clicks on the smaller button then decrease by 5.

Hint: If you are unfamiliar with using Buttons in Applets here is a template that handles the Buttons for you.


3

Create a new class called SuperFerry. It will extend Ferry. A SuperFerry is like a Ferry except that:
  1. it has a new method moveRelative(int deltaX, int deltaY) that moves the SuperFerry relative to its current position instead of to absolute coordinates.
  2. it looks like this ie. a Ferry with a roof.
Write an applet that demostrates that the SuperFerry's new methods work as well as the inherited ones.

Consider the following applet. It will illustrate another interesting facet of inheritance. It will display the vehicle of your choice. When you press the button labelled Move & Change Colour the vehicle you've selected will get moved to a random location and cycle throught the colours red, green and blue. The interesting thing is that the variable used to move and change colour is of type Vehicle. We can use that one variable regardless of what type of Vehicle we are using. Try out the applet and we'll get to more details following it.

At the beginning of the applet we have the statement:

Vehicle v;
Here is the code that creates the vehicle when you press a button (in the method actionPerformed):
if (e.getSource() == vehicleButton)
   v = new Vehicle(30,50,60,40,this);
else if (e.getSource() == carButton)
   v = new Car(30,50,60,40,this);
else if (e.getSource() == boatButton)
   v = new Boat(30,50,60,40,this);
else if (e.getSource() == ferryButton)
   v = new Ferry(30,50,60,40,this);
v.setVisible(true);
If Java is so particular about types, how can we get away with this? Well, it's not like trying to assign a double to a char for instance. These types are related to each other because they are all in the same inheritance heirarchy. The rule is that any superclass variable can hold a reference to itself or any subclasses. So a variable of type Vehicle can hold a reference to any of Vehicle, Car, Boat, Ferry or SuperFerry.

1

Answer
a) What type of references can a Car hold?
b) What type of references can a Boat hold?

Here is an inheritance diagram that shows what methods are available to each class. It also shows where the methods are defined, inherited or overridden.

So why not use the Mega-Superclass Object as the type for all our references? Since it is the superclass of all objects we can assign any object to it. What would have happened in the previous applet if we had declared v to be of type Object instead of Vehicle? As it turns out not much. Although we can create the Vehicles we can't use them. The only methods we can use are ones that are defined in Object, not Vehicle or its subclasses. Object doesn't have methods like move or setVisible. When v is defined as type Vehicle we can use any methods that are defined in Vehicle or its superclasses (in this case Object is the only superclass). This concept is so snazzy it has an equally snazzy name. It is called polymorphism.

2

Answer
Suppose we had the following statement:

Vehicle v = new SuperFerry(this);

State which of the following statements would be valid. For those that are invalid state why.

  1. v.setVisible(true);
  2. v.moveRelative(20, 30);
  3. v.setSize(50, 80);

We're finished with the Vehicles now. Try the following programs if you want to check that all the concepts make sense so far.


Programming question #4 (all 3 parts) is something I usually use as assignment after we've played with the vehicles for awhile. It usually takes a couple of weeks for the students to work on. They try to come up with a creative way to use the Face, HappyFace and Bunny classes to demonstrate that all the methods work. Part of the mark is based on creativity and originality. Often they decide to make their own subclasses on top of what is required.

4a

You are going to create several different kinds of Faces. The base class will be called Face. It will be very similar to the Vehicle class we were looking at. A Face looks like this:

Here is a list of the fields:
  • int x - the x-coordinate of the top left corner of the Face
  • int y - the y-coordinate of the top left corner of the Face
  • int diameter - the diameter of the circle for the Face
  • Color colour - the colour of the circle for the Face
  • Color eyeColour - the colour of the eyes
  • boolean isVisible - tells if the Face is showing or hiding
Here is a list of all the methods it will need:
  • public Face(Applet a) - sets up default values for the Face
  • public Face(int x, int y, int r, Color c, Color eyeC, Applet a) - allows you to set initial values for all the fields
  • public void draw() - draws a Face
  • public void erase() - erase a Face
  • public void setVisible (boolean visible) - hides or shows a Face
  • public void move(int x, int y) - move the Face to the given coordinates
  • public void setSize(int d) - change the diameter of the Face
  • public void setColor(Color c) - change the colour of the Face
  • public void setEyeColor(Color c) - change the eye colour
  • public int getX() - returns the x field
  • public int getY() - returns the y field

Write an applet that demonstrates that you have successfully implemented all these methods.


4b

You are now going to make a different kind of Face. This class will be called HappyFace. It will be very similar to the Face class. It will have a smile as well as eyes. It looks like this:

Its methods will be a little different as well. Here is a list of those methods:
  • public void move(int newX, int newY) - override the Face move so that the HappyFace moves slowly along a path to its new location, instead of instantly moving there as the Face move would do
  • public void wink(int howMany) - howMany controls how many times one eye will wink (change from a circle to a line)
  • public void laugh(int howLong) - it causes a laugh bubble to stay on the screen for a length of time determined by howLong (a time in milliseconds). It looks like this:
You will need to override the draw() and erase() methods as well.

Write an applet that demonstrates that you have successfully implemented all these methods.


4c

You are now going to make another subclass of Face. This class will be called Bunny. It will be very similar to the Face class. It will have bunny ears and a small mouth as well as eyes. It looks like this:
It will have some additional fields. They are:
  • Color earColour - the colour of the Bunny's ears
  • boolean surpriseStatus - whether the Bunny is surprised or not
A surprised Bunny looks like this:
Its methods will be a little different as well. Here is a list of those methods:
  • public void hop(int howMany, int howHigh) - move the Bunny howHigh pixels above its current position, pause and move back. Do this howMany times.
  • public void setEarColor(Color colour) - changes the ear's colour to colour
  • public void setSurprise(boolean status) - change the surpriseStatus and redraw with an appropriate mouth
You will need to override the draw() and erase() methods as well.

Write an applet that demonstrates that you have successfully implemented all these methods.


3

Answer
  1. List all the fields available in Bunny. Indicate which class they were defined in.
  2. Ignoring the methods from Object, which methods are available in Bunny. Indicate which class they were defined in or if they were overridden in Bunny.


Here are some questions based on what we've been discussing so far:

4

Answer
Consider a class that has the following form:
public class MyDate
{
   int year, month, day;

   /** Only the method signatures are given **/
   public MyDate() // a method to intialize a date to Jan. 1, 1900
   //set all fields. 1=Jan.,2=Feb.,...
   public void setDate(int yr, int mn, int dy)
   // returns a string in the form July 5, 2001
   public String toString()
   // allows the entry of a date from the keyboard
   public void enterDate()
}

Answer the following questions:

  1. Implement the setDate method.
  2. Implement the toString() method.
  3. If you were implementing the enterDate method what consideration would you need to make?
  4. Write a fragment of code that will have a MyDate object called date. Set the date to today's date. Print the date. Read a new date from the keyboard. Print the date.
  5. Suppose you were going to create a new class DateTime that will inherit from MyDate. In addition to storing a date the new class will allow you to store a time in 24 hour format. It will have three additional fields: hour, minute and second. It will override the toString method to produce a string in the format: July 5, 2001 - 4:52:11 p.m..
    1. Give the definition of the class (just give method signatures - don't fully implement)
    2. Would the following be legal? Explain.
      DateTime dt = new MyDate();

5

Answer
Consider the following class:
public class Sequence
{
   double a;
   public Sequence() {a = 0;}
   public Sequence(double t1) {a = t1;}
   public void setT1(double t1) {a = t1;}
   public double t(int n) {return ((n - 1) + a)* n;}
   public String toString() {return ""+a+", "+t(2)+", "+t(3)+", ...";}
}

Answer the following questions:

  1. Write a Java application that makes the first term in a Sequence be 4. Print the first three terms in the sequence. Find and print the sum of the first 5 terms in the sequence.
  2. Define a new class MySequence that uses a formula of tn = n2 to generate sequences.
  3. Define a new class Series that extends Sequence. It has a method double sum(int n) that finds the sum of the first n terms in the series. It will override toString() to insert "+" instead of "," in the string. It will have a method String sumString(int n) that will make a String of the form: t1 + t2 + t3 + ... + tn = Sn. For example, if we have a sequence as in part (a) then sumString(5) would generate a String of the form: "4.0 + 10.0 + 18.0 + ... + 40.0 = 100.0". If n <= 4 just print the whole series.

This concludes the first part of this resource. You are now ready to go to Part 2. It discusses inheritance in the context of the Java language, particularly with respect to GUIs and Swing. Students tend to really go for this stuff.