Classes (classdef)
So far you've grouped data in structures and behaviour in functions. A class puts the two together: it defines what data an object holds (its properties) and what you can do with it (its methods). MATLAB's own types work this way, and with classdef you can write your own.
A class is defined in a file of its own, named after the class (Rectangle.m for classdef Rectangle). In this course, a line % --- file: Rectangle.m after the script starts that file.
| Block | Contains |
|---|---|
classdef Name … end |
The whole class |
properties … end |
Data fields, optionally with default values |
methods … end |
Functions that work on objects, including the constructor |
methods (Static) |
Functions that belong to the class rather than to an object |
properties (Constant) |
Fixed values shared by every object |
properties (Dependent) |
Values computed on the fly from other properties |
A first class
r = Rectangle(3, 2);
fprintf('area %g, perimeter %g\n', r.area(), perimeter(r));
r.Width = 5; % properties are read and set with dots
fprintf('new area %g\n', r.area());
empty = Rectangle(); % no inputs: the defaults are used
fprintf('default: %g x %g\n', empty.Width, empty.Height);
% --- file: Rectangle.m
classdef Rectangle
properties
Width = 1
Height = 1
end
methods
function obj = Rectangle(w, h)
% Constructor: same name as the class, returns the new object
if nargin > 0
obj.Width = w;
obj.Height = h;
end
end
function a = area(obj)
a = obj.Width * obj.Height;
end
function p = perimeter(obj)
p = 2 * (obj.Width + obj.Height);
end
end
endarea 6, perimeter 10
new area 10
default: 1 x 1
Points to notice:
- The constructor is the method named like the class. It receives the inputs of
Rectangle(3, 2)and returns the object. Checkingnarginlets the class also be created with no inputs, which MATLAB needs, for instance, to build arrays of objects. - Every ordinary method receives the object as its first input (called
objby convention).r.area()andarea(r)are the same call. - Properties without a default start as
[].
Value semantics: methods return the changed object
Classes like this one are value classes: assigning an object copies it, exactly as with numbers and structs. A method can't change the caller's object in place; it must return the modified copy, and the caller must store it:
a = Counter();
a = a.increment();
a = a.increment();
b = a; % b is an independent copy
b = b.increment();
fprintf('a.Count = %d, b.Count = %d\n', a.Count, b.Count);
a.increment(); % result thrown away: a does not change
fprintf('a.Count is still %d\n', a.Count);
% --- file: Counter.m
classdef Counter
properties
Count = 0
end
methods
function obj = increment(obj)
obj.Count = obj.Count + 1;
end
end
enda.Count = 2, b.Count = 3
a.Count is still 2
Forgetting a = ... is the most common mistake with value classes. If you want objects that are shared and changed in place, use a handle class instead, the topic of Handle Classes & Events.
Controlling access
Property attributes decide who may read or write a property:
| Attribute | Meaning |
|---|---|
SetAccess = private |
Anyone can read it; only the class's methods can change it |
SetAccess = protected |
Like private, but subclasses may change it too |
Access = private |
Hidden completely from code outside the class |
GetAccess = private |
Can't be read from outside |
Methods accept Access = private too, for helpers that are only called by other methods.
acct = Account('Ada', 100);
acct = acct.deposit(50);
fprintf('%s has %g\n', acct.Owner, acct.Balance);
try
acct.Balance = 1e6; % not allowed from outside the class
catch
disp('Balance can only be changed through deposit.')
end
% --- file: Account.m
classdef Account
properties
Owner = ''
end
properties (SetAccess = private)
Balance = 0
end
methods
function obj = Account(owner, balance)
obj.Owner = owner;
obj.Balance = balance;
end
function obj = deposit(obj, amount)
obj.Balance = obj.Balance + obj.checked(amount);
end
end
methods (Access = private)
function x = checked(~, x)
if ~isscalar(x) || x <= 0
error('Account:badAmount', 'Amount must be a positive number.');
end
end
end
endAda has 150
Balance can only be changed through deposit.
Dependent properties and set methods
A Dependent property has no stored value. Reading it calls a get.Name method that computes it, and writing it (if allowed) calls set.Name. An ordinary property can also have a set.Name method, which runs on every assignment: the natural place for validation.
t = Temperature(25);
fprintf('%g C = %g F\n', t.Celsius, t.Fahrenheit);
t.Fahrenheit = 212; % runs set.Fahrenheit
fprintf('%g F = %g C\n', t.Fahrenheit, t.Celsius);
try
t.Celsius = -300; % runs set.Celsius, which refuses it
catch err
disp(err.message)
end
% --- file: Temperature.m
classdef Temperature
properties
Celsius = 0
end
properties (Dependent)
Fahrenheit
end
properties (Constant)
AbsoluteZero = -273.15
end
methods
function obj = Temperature(c)
if nargin > 0
obj.Celsius = c;
end
end
function f = get.Fahrenheit(obj)
f = obj.Celsius * 9/5 + 32;
end
function obj = set.Fahrenheit(obj, f)
obj.Celsius = (f - 32) * 5/9;
end
function obj = set.Celsius(obj, c)
if c < Temperature.AbsoluteZero
error('Temperature:tooCold', '%g C is below absolute zero.', c);
end
obj.Celsius = c;
end
end
end25 C = 77 F
212 F = 100 C
-300 C is below absolute zero.
Dependent properties can never be out of date, because they are recomputed each time. Use them for values derived from others (an area from a width and height, a full name from first and last).
Static methods and constants
Constant properties and Static methods belong to the class itself, so you use them through the class name, without an object. Static methods are often used as alternative constructors ("factory methods"):
fprintf('absolute zero: %g C\n', Temperature.AbsoluteZero);
t = Temperature.fromFahrenheit(98.6);
fprintf('body temperature: %.1f C\n', t.Celsius);
% --- file: Temperature.m
classdef Temperature
properties
Celsius = 0
end
properties (Constant)
AbsoluteZero = -273.15
end
methods
function obj = Temperature(c)
if nargin > 0
obj.Celsius = c;
end
end
end
methods (Static)
function obj = fromFahrenheit(f)
obj = Temperature((f - 32) * 5/9);
end
end
endabsolute zero: -273.15 C
body temperature: 37.0 C
Displaying objects and object arrays
Leaving off the semicolon shows the class name and its public properties. To control what users see, define a disp method. Objects of the same class can also be collected in an array and indexed like any other array:
p = Point(1, 2)
pts = [Point(0, 0), Point(3, 4), Point(6, 8)];
fprintf('%d points\n', numel(pts));
d = zeros(size(pts));
for k = 1:numel(pts)
d(k) = pts(k).dist(); % index the array, then call the method
end
disp(d)
fancy = Point2(3, 4);
disp(fancy)
% --- file: Point.m
classdef Point
properties
X = 0
Y = 0
end
methods
function obj = Point(x, y)
if nargin > 0
obj.X = x;
obj.Y = y;
end
end
function d = dist(obj)
d = hypot(obj.X, obj.Y);
end
end
end
% --- file: Point2.m
classdef Point2
properties
X = 0
Y = 0
end
methods
function obj = Point2(x, y)
obj.X = x;
obj.Y = y;
end
function disp(obj)
fprintf('Point2(%g, %g)\n', obj.X, obj.Y);
end
end
endp =
1x1 Point object with properties:
X: 1
Y: 2
3 points
0 5 10
Point2(3, 4)
The default display above is Octave's layout. MATLAB shows the same information as Point with properties: followed by the property values.
Inspecting a class
| Function | Returns |
|---|---|
class(obj) |
The class name |
isa(obj, 'Name') |
true if obj is a Name (or a subclass of it) |
properties(obj) |
The public property names |
methods(obj) |
The method names |
isprop(obj, 'P'), ismethod(obj, 'm') |
Whether a property or method exists |
r = Rectangle(2, 5);
fprintf('class: %s, isa Rectangle: %d\n', class(r), isa(r, 'Rectangle'));
fprintf('properties: %s\n', strjoin(properties(r)', ', '));
fprintf('has area: %d, has volume: %d\n', ismethod(r, 'area'), ismethod(r, 'volume'));
% --- file: Rectangle.m
classdef Rectangle
properties
Width = 1
Height = 1
end
methods
function obj = Rectangle(w, h)
if nargin > 0
obj.Width = w;
obj.Height = h;
end
end
function a = area(obj)
a = obj.Width * obj.Height;
end
end
endclass: Rectangle, isa Rectangle: 1
properties: Width, Height
has area: 1, has volume: 0
MATLAB-only class features
Property validation. MATLAB can declare a size, class and validators for each property, checked on every assignment:
classdef Box
properties
Width (1,1) double {mustBePositive} = 1
Label (1,:) char = 'box'
end
end>> b = Box;
>> b.Width = -3
Error setting property 'Width' of class 'Box'. Value must be positive.(MATLAB output.) Octave 11 accepts the syntax but prints a warning that it does not check it yet. For portable code, validate in a set.Width method as in the Temperature example.
Enumerations. A class with an enumeration block defines a fixed set of named values:
classdef Level
enumeration
Low, Medium, High
end
end>> x = Level.Medium
x =
Level enumeration
Medium
>> x == Level.High
ans =
logical
0(MATLAB output. Octave 11 does not support enumeration blocks.) In Octave, use char constants ('low', 'medium') checked with validatestring, or Constant properties.
Classes or structs?
Use a struct for plain data passed between functions. Reach for a class when the data has rules (valid ranges, read-only fields), when several functions always travel with the same data, or when you want different kinds of objects to respond to the same method name, which inheritance makes possible.
Learn more: Handle Classes & Events, Inheritance & Operator Overloading and Input Validation.
Test yourself
In a value class, a method increment returns the changed object. What does c.increment(); (without assignment) do to c?
- Increments it
- Nothing: the changed copy is discarded
- Raises an error
- Deletes it
What does SetAccess = private on a property mean?
- Nobody can read it
- Only class methods can change it, but anyone can read it
- It is computed on the fly
- It is shared by all objects
How do you call a Static method fromFahrenheit of class Temperature?
fromFahrenheit(98.6)Temperature.fromFahrenheit(98.6)obj.Temperature(98.6)static(98.6)