Next page | Contents page |

Inheritance

Consider a class similar to one we saw earlier:

public class Circle
{
	private double radius;
	
	public double getRadius () { return radius; }
	
	public Circle (double aRadius)
	{
		radius = aRadius;
	} // Circle
	
	public double area ()
	{
		return Math.PI * radius * radius;
	} // area
	
	public float perimeter ()
	{
		return 2.0 * Math.PI * radius;
	} // perimeter
	
} // Circle

To specify a circle at a given position on a sheet of paper we would also want to give the position of the centre of the circle. Rather than modify class Circle we might write a subclass, called CentredCircle, that has the extra information and methods using it. We use the keyword extends after the class name:

import java.awt.Point;

public class CentredCircle extends Circle
{
	private Point centre;
	
	public Point getCentre () { return centre; }
	
	public CentredCircle (Point aCentre, double aRadius)
	{
		super (aRadius); // Call the superclass constructor
		centre = aCentre; // Set the extra field
	} // CentredCircle
	
} // CentredCircle

CentredCircle inherits the fields and methods of Circle. We only have to write the extra bits.

Remember that a CentredCircle is a Circle, a more specialised one. Any method that requires a Circle as an input will accept a CentredCircle (but not vice versa: a Circle is not a CentredCircle).

You can only extend one immediate superclass (this is another thing that those who have used C++ before may find limiting, but you will see soon that Java has another way of doing multiple inheritance that has many advantages).

Overriding methods

Instance methods with exactly the same name and the same parameters as one in a superclass override the latter, so they are invoked instead, for instances of the subclass. The method in the superclass can still be invoked from the subclass by using super. as a prefix (but that is rarely necessary).

To prevent the possibility of overriding you can use the modifier final when declaring a method in a class.

NB: 2 methods of same name, different parameters = "overloading", not to be confused with "overriding".

Abstract classes

Some classes are designed never to be instantiated. They have to be extended in order to make any objects. This is achieved by putting the modifier keyword abstract in front of the class name. Such a class can contain methods without any bodies, for the inheriting subclass to write the complete version (thereby "overriding" them). Such a method would be written like this:

public void myMethod (String param);

End the declaration with a semicolon instead of curly braces.

Final classes

If instead you put the modifier final in front of a class declaration it means that no-one will be able to extend it. The API class java.lang.String is final, to prevent anyone getting around the immutability requirement.

Next page | Contents page |