Inheritance & Operator Overloading
Inheritance lets one class build on another: a Circle is a Shape, so it gets everything a Shape has and adds or changes what is different. Operator overloading lets your objects work with +, ==, < and friends, so a Money or Vector class reads like built-in arithmetic. Both build on Classes (classdef).
| Term | Meaning |
|---|---|
| Superclass (base class) | The class being extended, e.g. Shape |
| Subclass (derived class) | The new class: classdef Circle < Shape |
| Override | A subclass method with the same name replaces the superclass version |
obj@Shape(args) |
Calls the superclass constructor from the subclass constructor |
name@Shape(obj, ...) |
Calls the superclass version of an overridden method |
A small hierarchy
The base class holds what every shape has (a name) and the behaviour that is the same for all (describe). Each subclass adds its own properties and overrides area:
c = Circle(2);
s = Square(3);
disp(c.describe())
disp(s.describe())
fprintf('Circle is a Shape: %d\n', isa(c, 'Shape'));
fprintf('Circle is a Square: %d\n', isa(c, 'Square'));
% --- file: Shape.m
classdef Shape
properties
Name = 'shape'
end
methods
function obj = Shape(name)
if nargin > 0
obj.Name = name;
end
end
function a = area(obj)
error('Shape:abstract', '%s must implement area.', class(obj));
end
function s = describe(obj)
s = sprintf('%s with area %.2f', obj.Name, obj.area());
end
end
end
% --- file: Circle.m
classdef Circle < Shape
properties
Radius = 1
end
methods
function obj = Circle(r)
obj@Shape('circle'); % run the Shape constructor first
obj.Radius = r;
end
function a = area(obj)
a = pi * obj.Radius^2;
end
end
end
% --- file: Square.m
classdef Square < Shape
properties
Side = 1
end
methods
function obj = Square(side)
obj@Shape('square');
obj.Side = side;
end
function a = area(obj)
a = obj.Side^2;
end
end
endcircle with area 12.57
square with area 9.00
Circle is a Shape: 1
Circle is a Square: 0
describe is written once, in Shape, yet it prints the right area for each object: obj.area() calls the version that belongs to the object's actual class. This is polymorphism: the same call, different behaviour depending on the object.
The superclass constructor call obj@Shape(...) must come before you use obj in the subclass constructor. If you leave it out, MATLAB calls the superclass constructor with no inputs, so the superclass must then handle nargin == 0.
Polymorphism in a loop
Objects of different classes can't sit in one ordinary array, but a cell array holds anything. The loop doesn't need to know which shape it's looking at:
shapes = {Circle(1), Square(2), Circle(0.5), Square(1.5)};
total = 0;
for k = 1:numel(shapes)
sh = shapes{k};
fprintf('%-7s %6.3f\n', class(sh), sh.area());
total = total + sh.area();
end
fprintf('total %6.3f\n', total);
% --- file: Shape.m
classdef Shape
methods
function a = area(obj)
error('Shape:abstract', '%s must implement area.', class(obj));
end
end
end
% --- file: Circle.m
classdef Circle < Shape
properties
Radius = 1
end
methods
function obj = Circle(r)
obj.Radius = r;
end
function a = area(obj)
a = pi * obj.Radius^2;
end
end
end
% --- file: Square.m
classdef Square < Shape
properties
Side = 1
end
methods
function obj = Square(side)
obj.Side = side;
end
function a = area(obj)
a = obj.Side^2;
end
end
endCircle 3.142
Square 4.000
Circle 0.785
Square 2.250
total 10.177
(MATLAB can also put mixed subclasses in a real array if the base class inherits from matlab.mixin.Heterogeneous; Octave doesn't support that mixin.)
Extending, not replacing, a method
An override often wants to do what the superclass did plus something more. Call the superclass version with method@Superclass(obj, ...):
e = Employee('Grace', 'Engineering');
disp(e.label())
% --- file: Person.m
classdef Person
properties
Name = ''
end
methods
function obj = Person(name)
obj.Name = name;
end
function s = label(obj)
s = ['Name: ' obj.Name];
end
end
end
% --- file: Employee.m
classdef Employee < Person
properties
Dept = ''
end
methods
function obj = Employee(name, dept)
obj@Person(name);
obj.Dept = dept;
end
function s = label(obj)
base = label@Person(obj); % the Person version
s = [base ', Dept: ' obj.Dept];
end
end
endName: Grace, Dept: Engineering
Store the result of label@Person(obj) in a variable before using it: Octave 11 doesn't accept the @ call inside a [...] concatenation.
Abstract classes (MATLAB)
A Shape that can't compute its own area shouldn't really be created at all. MATLAB lets you mark the class and the method abstract: subclasses must implement it, and Shape() itself is refused:
classdef (Abstract) Shape
methods (Abstract)
a = area(obj) % no body: subclasses must provide it
end
end>> s = Shape()
Error using Shape
Abstract classes cannot be instantiated. Class 'Shape' defines abstract methods and/or properties.(MATLAB output.) Octave 11 doesn't support methods (Abstract) blocks: it rejects the file. The portable substitute is what the examples above do: a normal method that raises an error saying the subclass must implement it.
Overloading operators
Each operator calls a method with a fixed name. Define that method in your class and the operator works on your objects:
| Operator | Method | Operator | Method |
|---|---|---|---|
a + b |
plus(a, b) |
a == b |
eq(a, b) |
a - b |
minus(a, b) |
a ~= b |
ne(a, b) |
-a |
uminus(a) |
a < b, a > b |
lt, gt |
a .* b, a * b |
times, mtimes |
a <= b, a >= b |
le, ge |
a ./ b, a / b |
rdivide, mrdivide |
~a, a & b, a | b |
not, and, or |
| display | disp(a) |
conversion | double(a), char(a) |
a = Vec2(1, 2);
b = Vec2(3, -1);
disp(a + b)
disp(a - b)
disp(2 * a) % number * Vec2
disp(a * 3) % Vec2 * number
disp(-b)
fprintf('|b| = %.4f\n', norm(b));
fprintf('a == b: %d, a == Vec2(1, 2): %d\n', a == b, a == Vec2(1, 2));
% --- file: Vec2.m
classdef Vec2
properties
X = 0
Y = 0
end
methods
function obj = Vec2(x, y)
if nargin > 0
obj.X = x;
obj.Y = y;
end
end
function r = plus(a, b)
r = Vec2(a.X + b.X, a.Y + b.Y);
end
function r = minus(a, b)
r = Vec2(a.X - b.X, a.Y - b.Y);
end
function r = uminus(a)
r = Vec2(-a.X, -a.Y);
end
function r = mtimes(a, b)
% one input is a number, the other a Vec2, in either order
if isnumeric(a)
[a, b] = deal(b, a);
end
r = Vec2(a.X * b, a.Y * b);
end
function t = eq(a, b)
t = a.X == b.X && a.Y == b.Y;
end
function n = norm(a)
n = hypot(a.X, a.Y);
end
function disp(a)
fprintf('(%g, %g)\n', a.X, a.Y);
end
end
end(4, 1)
(-2, 3)
(2, 4)
(3, 6)
(-3, 1)
|b| = 3.1623
a == b: 0, a == Vec2(1, 2): 1
Note how 2 * a works: MATLAB calls the mtimes method of whichever input is an object, so mtimes receives (2, a) and must handle the number coming first. Overloading norm shows that any function name can be overloaded, not just operators.
Comparisons and conversions
Comparison operators make objects sortable by hand, and a char method gives a natural way to print them:
prices = {Money(4.5), Money(12), Money(0.99)};
cheapest = prices{1};
for k = 2:numel(prices)
if prices{k} < cheapest
cheapest = prices{k};
end
end
fprintf('cheapest: %s\n', char(cheapest));
total = prices{1} + prices{2} + prices{3};
fprintf('total: %s\n', char(total));
fprintf('as a number: %.2f\n', double(total));
fprintf('12 > 4.50: %d\n', prices{2} > prices{1});
% --- file: Money.m
classdef Money
properties (SetAccess = private)
Cents = 0
end
methods
function obj = Money(amount)
obj.Cents = round(amount * 100); % store whole cents: no rounding drift
end
function r = plus(a, b)
r = Money((a.Cents + b.Cents) / 100);
end
function t = lt(a, b)
t = a.Cents < b.Cents;
end
function t = gt(a, b)
t = a.Cents > b.Cents;
end
function d = double(a)
d = a.Cents / 100;
end
function s = char(a)
s = sprintf('$%.2f', a.Cents / 100);
end
end
endcheapest: $0.99
total: $17.49
as a number: 17.49
12 > 4.50: 1
Guidelines
- Use inheritance for a genuine "is a" relationship. If a class merely uses another one ("a car has an engine"), store an object in a property instead (composition).
- Keep hierarchies shallow; two levels are usually enough.
- Overload an operator only when its meaning is obvious.
+for vectors or money is natural;+meaning "append to a log" is not. - When an operator mixes objects and numbers, handle both argument orders.
- A subclass of a handle class is a handle class too, and everything in Handle Classes & Events applies.
Learn more: the same ideas in other languages: Python inheritance and C++ operator overloading.
Test yourself
Which line in a subclass constructor calls the superclass constructor?
super(obj, args)obj@Shape(args);Shape.obj(args);obj = Shape(args);
Which method must a class define so that a + b works on its objects?
addplussumoperator+
What does 2 * v pass to the mtimes method of v's class?
(v, 2)(2, v)- Only
v - Nothing; it is an error