Appearance
Inheritance
A superclass/subclass relationship may exist between two classes when one class "is a kind of" the other class. Subclasses inherit the structure and behavior of their superclass.
java
public abstract class Shape {
public abstract double area();
public abstract double circumference();
}
java
class Circle extends Shape {
public static final double PI = 3.14159265358979323846;
protected double r;
public Circle(double r) { this.r = r; }
public double getRadius() { return r; }
public double area() { return PI*r*r; }
public double circumference() { return 2*PI*r; }
}
java
class Rectangle extends Shape {
protected double w, h;
public Rectangle(double w, double h) {
this.w = w; this.h = h;
}
public double getWidth() { return w; }
public double getHeight() { return h; }
public double area() { return w*h; }
public double circumference() { return 2*(w + h); }
}
Class inheritance provides a way to organize classes into a type hierarchy which is a powerful model to capture the complexity of many real-world problems, in particular, those naturally exhibit a hierarchical structure.
Moreover, inheritance promotes code reuse, since common behavior and attributes can be defined once in the superclass rather than repeated in each subclass. That said, inheritance should be used when one class "is a kind of" the other class not to merely leverage code reuse. For code reuse, favor composition over inheritance.
Object Composition
Another effective way to reuse code (but without inheritance) is through object composition which, in a nutshell, is a way to combine objects into more complex ones. (E.g., put a Cooktop
and an Oven
together to get a Stove
!)