Inheritance

In writing OO programs it is normal to make use of classes which have been written for us (or previously written by us). Sometimes there is a class available for us to use which is close to our requirements, but not exactly what we want. In this case we can use inheritance to modify an existing class to reuse code and avoid having to write new classes as often.

In this example we will look at a class which paints a circle on the screen with radius 20 in a specified position:

import java.awt.*;
public class Sphere
{

protected int x=100, y=100;
public void setX(int newX)
{

x = newX:

}
public void sety(int newY)
{

y = newY;

}
public void display(Graphics g)
{

g.drawOval(x,y,20,20);

}

}

So we can use this class to instatiate an object called 'ball' and we have methods to set the x and y coordinates and display the ball.

Now suppose we wish to instatiate an object called bubble, which can change size. Rather than write a new class we can use inheritance to extend the Sphere class.

import java.awt.*;
public class Bubble extends Sphere
{

protected int radius = 10;
public void setSize(int size)
{

radius = size;

}
public void display(Graphics g)
{

g.drawOval(x, y, 2*radius, 2*radius);

}

}

So the class Bubble has all the methods that Sphere had, with the added methods to change the size and display the correct size.

We call Bubble a sub-class of Sphere.

You will notice that we have actually been using inheritance already, as every applet we write is a sub-class of the Applet class.

Notice the use of the word protected as a variable declaration. Protected variables are between public and private, in the sense that the scope of those variables extends to subclasses, but not any other classes. In other words protected variables are inherited.

Note also that there is a new display method in Bubble. That is because the display method in Sphere was not suitable (it could not vary the size of the circle displayed.) This is referred to as overriding. Objects of type Bubble will have the new display method.

Bibliography
1. "Java for Students", Bell D. & Parr M., Pearson (2010), 6th Ed., pp 194
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License