Same action, different things
After this: Give two classes a method with the same name, and say which one runs for each object.
On this page · 7 sections · 3 checks
A gardener is laying turf. There is a round pond and a rectangular lawn, and the question for each is the same: what is your area? The working is different. For the pond it is pi times the radius times the radius. For the lawn it is width times height. One question, two ways to answer it.
Programs meet this all the time. Several kinds of thing can do the same action, each in its own way. This tutorial is about writing that down, so that the program asks one question and each kind answers it correctly.
The same name in two classes
In Classes and objects, every method belonged to one class. Nothing stops two classes from each having a method with the same name. A Circle can have area, and a Rect can have area. They are two different methods that happen to share a name.
When the program writes c.area(), which one runs? The object decides. c holds a circle, so the circle's area runs. For r.area() with a rectangle in r, the rectangle's area runs. The line that asks looks the same both times.
By hand
Take a circle with radius 1 and a rectangle 2 wide and 3 high.
- Ask the circle for its area. The circle's method works out pi times 1 times 1, which is 3.141592653589793. To two decimals, 3.14.
- Ask the rectangle for its area. The rectangle's method works out 2 times 3, which is 6.
- Both answers came from the same question,
area(). Only the working differed.
The rule: when two classes have a method with the same name, the object you call it on chooses which method runs. You never say which class; the object knows what it is.
The code
import math
class Circle: def __init__(self, r): self.r = r
def area(self): return math.pi * self.r * self.r
class Rect: def __init__(self, w, h): self.w = w self.h = h
def area(self): return self.w * self.h
c = Circle(1)r = Rect(2, 3)print(round(c.area(), 2))print(r.area())3.14 6
class Circle { int r;
Circle(int r) { this.r = r; }
double area() { return Math.PI * r * r; }}
class Rect { int w; int h;
Rect(int w, int h) { this.w = w; this.h = h; }
double area() { return w * h; }}
public class Main { public static void main(String[] args) { Circle c = new Circle(1); Rect r = new Rect(2, 3); System.out.println(String.format("%.2f", c.area())); System.out.println(r.area()); }}3.14 6.0
Walk through it.
Circlestores a radiusr. Itsareareturns pi timesrtimesr. Pi comes from the standard library, as math.piMath.PI, which Input, files and the standard library showed.Rectstoreswandh. Itsareareturnswtimesh.- The last four lines make one of each, then print the two areas. The circle's area has many decimals, so it is rounded to two for display with round(c.area(), 2)String.format("%.2f", c.area()). The number in the box keeps every decimal; only the display is rounded.
Watch it happen
Press Run it and step through. Two things to look for. First, each call to area opens a frame named area, and the frame's first box, selfthis, holds the object the method is working on: Circle(r=1) the first time and Rect(w=2, h=3) the second. The frame name is the same; the box tells the two calls apart. Second, the constructor call at the start: its frame opens with an empty Circle() in that box, and the box gains r on the next line.
- Run the programRun it and step through. Each time area is called, a frame named area opens. Read its first box: it holds the object the method is working on, a circle the first time and a rectangle the second.
import math
class Circle: def __init__(self, r): self.r = r
def area(self): return math.pi * self.r * self.r
class Rect: def __init__(self, w, h): self.w = w self.h = h
def area(self): return self.w * self.h
c = Circle(1)r = Rect(2, 3)print(round(c.area(), 2))print(r.area())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
Run it
Python runs in the browser when you press Run on the block below. Java does not run here: if you are learning Java, step through the trace above instead, and paste the code into a Java tool on your computer when you want to run it for real.
Change the radius to 2, or make the rectangle 4 by 5, and run it again.
Check yourself
A program holds a circle in c and a rectangle in r. Both classes have a method named area. What runs when the program calls r.area()?
The same two classes, with different sizes. What does this print?
import math
class Circle: def __init__(self, r): self.r = r
def area(self): return math.pi * self.r * self.r
class Rect: def __init__(self, w, h): self.w = w self.h = h
def area(self): return self.w * self.h
print(round(Circle(2).area(), 2))print(Rect(4, 5).area())class Circle { int r;
Circle(int r) { this.r = r; }
double area() { return Math.PI * r * r; }}
class Rect { int w; int h;
Rect(int w, int h) { this.w = w; this.h = h; }
double area() { return w * h; }}
public class Main { public static void main(String[] args) { System.out.println(String.format("%.2f", new Circle(2).area())); System.out.println(new Rect(4, 5).area()); }}Complete the area method of Rect so that the program prints the area of a 2 by 3 rectangle.
class Rect: def __init__(self, w, h): self.w = w self.h = h
def area(self): ____________________ # ← hand back the width times the height
r = Rect(2, 3)print(r.area())class Rect { int w; int h;
Rect(int w, int h) { this.w = w; this.h = h; }
double area() { ____________________ // ← hand back the width times the height }}
public class Main { public static void main(String[] args) { Rect r = new Rect(2, 3); System.out.println(r.area()); }}Honesty notes
- Say that two classes may each have a method with the same name, and that they are two different methods.
- Say which method runs for a call like r.area(): the one in the class of the object in r.
- Work out a circle's area (pi times the radius squared) and a rectangle's (width times height) by hand, and round for display.
- Read a method call in the trace band: the frame is named after the method, and its self box (this in Java) shows which object it works on.