Inheritance is a way of defining a new class in terms of an old one. The idea is to say: class B is like the existing class A, except with some differences such as:
We say that B extends A, and that B is derived from A, and that B is a subclass of A.
Suppose we have the Circle class:
class Circle
{
private double radius;
public Circle(double r) { radius = r; }
public double getRadius() { return radius; }
public double findCircumference() {
return 2*Math.PI*radius;
}
public double findArea() {
return radius*radius*Math.PI;
}
}
We want to define a Cylinder class. Cylinders are like Circles, but they have
another variable, their length.
public class Cylinder extends Circle
{
private double length;
public Cylinder(double r, double l) {
super(r); // calls Circle's constructor
length = l;
}
public double getLength() {
return length;
}
public double findArea() {
// overrides findArea in Circle
return 2*super.findArea()
+ findCircumference()*length;
}
public double findVolume() {
return super.findArea()*length;
}
}
All classes descend from Object. Here is part of a typical inheritance hierarchy:
A secretary is-a employee; an employee is-a person, etc.
Suppose class B extends class A. It is always possible to convert a B object into an A object. In this case, explicit casting can be omitted, e.g.,
Employee e = mySecr;
It is not necessarily possible to convert an A object into a B object. Even if it is possible, we have to cast it.
Secretary s = (Secretary) emplArr[i];
If anEmpl is not a Secretary, the interpreter throws an exception. The instanceOf operator can be used to detect whether an object is an instance of a class:
if (emplArr[i] instanceOf Secretary) {
s = (Secretary) emplArr[i];
...
}
Java does not support multiple inheritance, which is defining a class which extends several classes at once, because that is confusing. Instead, it has a notion of interface. An interface is like a class which has no instance variables; and it has method signatures, but no method bodies. For example, the Comparable interface is in java.lang:
public interface Comparable {
public int compareTo(Object o);
}
If a class is defined as implementing this interface, it means it has to have
a compareTo method with that signature. The idea is that compareTo
defines an ordering on objects of the class which implements the interface.
Thus, in the diagram below, Circle and Cylinder extend Geometric
(thus inheriting variables like position, colour) and implement Comparable
(thus promising to have a method compareTo which compares e.g. their
area). A class can implement several interfaces.
© 2001 Mark Ryan and Alan Sexton