A class built on another
After this: Build a child class on a parent, reuse the parent's constructor, and replace one method.
On this page · 8 sections · 4 checks
Every shape in a drawing program has a name and can describe itself. A circle also has a radius; a rectangle also has a width and a height. If you write describe inside Circle and again inside Rect, you have copied code, and a fix in one copy is a mistake waiting in the other.
In the last lesson the two classes stood alone. This lesson lets one class be built on another, so that what is shared is written once.
Building one class on another
means building a class on another one. The class you build on is the ; the class built on it is the . You will also hear superclass and subclass for the same pair.
The child starts with everything the parent has. It can add fields and methods of its own, and it can replace a method, which the second half of this lesson covers.
By hand
Shape has a name and a method describe that returns "a " and the name. Circle is built on Shape and adds a radius. Making Circle(1) and asking it to describe itself:
- The program calls Circle's constructor with
rholding 1. - Its first line, super().__init__("circle")super("circle"), runs Shape's constructor on the same object. Shape's constructor sets
nameto "circle". - Back in Circle's constructor, the next line sets
rto 1. The object now has anameand anr. c.describe(): Circle has nodescribeof its own, so the one inShaperuns, with the circle as its object. It returns "a circle".
The rule for finding a method: look in the object's own class first. If it is not there, look in the parent.
Watch it happen
Step through, and watch the selfthis box. It starts as an empty Circle(), gains name inside Shape's constructor, and gains r back in Circle's.
- Run the programRun it. Watch the object in the constructor's first box grow: empty at first, then with a name after the parent's constructor runs, then with r as well.
class Shape: def __init__(self, name): self.name = name
def describe(self): return "a " + self.name
class Circle(Shape): def __init__(self, r): super().__init__("circle") self.r = r
c = Circle(1)print(c.describe())print(c.r)run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
The code
class Shape: def __init__(self, name): self.name = name
def describe(self): return "a " + self.name
class Circle(Shape): def __init__(self, r): super().__init__("circle") self.r = r
c = Circle(1)print(c.describe())print(c.r)a circle 1
class Shape { String name;
Shape(String name) { this.name = name; }
String describe() { return "a " + name; }}
class Circle extends Shape { int r;
Circle(int r) { super("circle"); this.r = r; }}
public class Main { public static void main(String[] args) { Circle c = new Circle(1); System.out.println(c.describe()); System.out.println(c.r); }}a circle 1
Replacing a method
Sometimes the parent's version of a method is wrong for the child. Shape can have an area that returns 0.0, because a shape in general has no area to give, and Circle writes its own. Writing a method in the child with the same name as one in the parent is called an : for a circle, the child's version runs, and the parent's is not used.
import math
class Shape: def area(self): return 0.0
class Circle(Shape): def __init__(self, r): self.r = r
def area(self): return math.pi * self.r * self.r
s = Shape()c = Circle(1)print(s.area())print(round(c.area(), 2))run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
s is a plain Shape, so s.area() runs Shape's area and prints 0.0. c is a Circle, so c.area() runs Circle's and prints 3.14. The same call, a different method, chosen by the object.
import math
class Shape: def area(self): return 0.0
class Circle(Shape): def __init__(self, r): self.r = r
def area(self): return math.pi * self.r * self.r
s = Shape()c = Circle(1)print(s.area())print(round(c.area(), 2))0.0 3.14
class Shape { double area() { return 0.0; }}
class Circle extends Shape { int r;
Circle(int r) { this.r = r; }
@Override double area() { return Math.PI * r * r; }}
public class Main { public static void main(String[] args) { Shape s = new Shape(); Circle c = new Circle(1); System.out.println(s.area()); System.out.println(String.format("%.2f", c.area())); }}0.0 3.14
Run it
Add a class Rect built on Shape that passes "rectangle" to the parent, make one, and print its description.
Check yourself
Inside Circle's constructor, what does the line super().__init__("circle")super("circle"); do?
Complete the first line of Circle so that it is built on Shape and the program prints a shape.
class Shape: def describe(self): return "a shape"
____________________ # ← Circle, built on Shape def __init__(self, r): self.r = r
c = Circle(1)print(c.describe())class Shape { String describe() { return "a shape"; }}
____________________ // ← Circle, built on Shape int r;
Circle(int r) { this.r = r; }}
public class Main { public static void main(String[] args) { Circle c = new Circle(1); System.out.println(c.describe()); }}Circle replaces describe. What does this print?
class Shape: def describe(self): return "a shape"
class Circle(Shape): def describe(self): return "a circle"
print(Shape().describe())print(Circle().describe())class Shape { String describe() { return "a shape"; }}
class Circle extends Shape { @Override String describe() { return "a circle"; }}
public class Main { public static void main(String[] args) { System.out.println(new Shape().describe()); System.out.println(new Circle().describe()); }}Shape has a method area that returns 0.0. In Circle, built on Shape, you mean to replace it, but you type def aera(self): by mistake. What happens when the program calls c.area() on a circle?Shape has a method area that returns 0.0. In Circle, built on Shape, you mean to replace it, but you type @Override double aera() by mistake. What happens?
Honesty notes
- Say what inheritance is: a child class built on a parent class starts with every field and method of the parent.
- Write the first line of a child class (the parent in brackets in Python, extends in Java).
- Say what super does: it runs the parent's constructor on the same object, so that the parent's fields are set.
- Override a method: write it again in the child, and say that the child's version runs for the child's objects.
- Say what Java's @Override checks, and what happens in Python when a child misspells the method name.