Inheritance
The biggest draw of OOP
is its inheritance
property.

Inheritance
is the mechanism that binds two classes in a parent-child relationship. In this relationship, the child can access all the properties and methods of the parent. An object can originate from a more specific type of the parent class which allows you to inherit that object as a child from its parent class. If the behavior of the child class needs to change, we can override or add to the methods of the parent class to work as we want. We cannot change the function signature though.
In the Shape
class example, think of a Circle
or a Rectangle
. Both of these objects also need a getMaxArea
method, a maxWidth
property, and a maxHeight
property. Instead of reimplementing the same methods for these new classes by copy-pasting, we can just inherit these two classes from the Shape
class.
Let's implement it now! Java has a keyword extends
which applies inheritance to a class. See the example below.
1// Circle.java
2public class Circle extends Shape {
3 // Here, we don't need to define maxHeight and maxWidth. They are already defined
4 // Later we will learn how to initialize these when we learn about constructors
5
6 // Adding new properties
7 private int radius;
8
9 // Adding new methods
10 public int getRadius() { return radius; }
11 public void setRadius(int radius) { this.radius = radius; }
12 public double getArea() {
13 return 3.14*radius*radius;
14 }
15}
16
17// Rectangle.java
18public class Rectangle extends Shape {
19 private int height;
20 private int width;
21
22 // Adding new methods
23 public int getHeight() { return height; }
24 public int getWidth() { return width; }
25 public void setWidth(int width) { this.width = width; }
26 public void setHeight(int height) { this.height = height; }
27 public int getArea() {
28 return height*width;
29 }
30}
31
32// Main.java
33public class Main {
34 public static void main(String[] args) {
35 Circle circle = new Circle();
36 // Calling circle's own methods
37 System.out.println(circle.getArea());
38 // Calling parent classes methods
39 System.out.println(circle.getMaxArea());
40 }
41}
Note that, inheritance is only allowed if the two objects can be thought of as the same or similar. A circle is a shape. A rectangle is also a shape.
On the other hand, if we wanted to implement a Line
class, then it could not be inherited from Shape
since a line is not a shape. Also, it should not have methods like getArea
. However, a shape can contain a number of lines. We will discuss this more when we talk about Composition and Association in a later lesson.