FUNCTION REFERENCE
classdef
Define a value or handle class in a class file.
Define a value or handle class in a class file.
Syntax
classdef Name ... endSyntax
classdef (Sealed) Name ... endSyntax
classdef Name < handle ... endSyntax
classdef Name < Super1 & Super2 ... endPut the definition in Name.mr or Name.m in the Current Folder, as for a function file; comments and blank lines may come before classdef. Name(args) calls the constructor, the method named like the class, function obj = Name(args), where obj starts as the default object. A class without a constructor makes the default object from Name().
A file Pt.m with these lines:
classdef Pt
properties
x = 0
label = 'a'
end
properties (Constant)
Origin = 0
end
methods
function obj = Pt(x)
if nargin > 0
obj.x = x;
end
end
function obj = shift(obj, d)
obj.x = obj.x + d;
end
end
methods (Static)
function p = unit()
p = Pt(1);
end
end
endlets you write p = Pt(3), p = p.shift(1), p = shift(p, 2), u = Pt.unit() and Pt.Origin.
Blocks: properties takes (Access, GetAccess or SetAccess = public, protected or private), (SetAccess = immutable), (Constant), (Dependent), (Hidden) and (Transient); each line is name, optional validation `(dims) class {validators}` and optional `= expression` default. Property validation converts class, checks size, and runs validators on defaults and on every property assignment (including constructor, indexed assignment `obj.P(i) = v`, and `set(obj, 'P', v)` for handle classes). All defaults, Constant or not, are evaluated in declaration order once per run, when the class is first loaded (the first Name(...), Name.Const, Name.method(...), methods('Name'), properties('Name') or use of an object from an earlier run, not at each construction), in a workspace with no variables; a default may call functions and read Name.Const of the same class. A default that makes a handle object gives every new object that same handle, as in MATLAB. methods takes (Static), (Access = ...) and (Abstract); every method ends with end (in a class folder a signature without a body names a method kept in its own file, see below). Local functions may follow the classdef end; only the class's methods see them.
Value objects: b = a; b.x = 1 leaves a unchanged, and a method must return the changed object (p = p.shift(1)). p.x, p.x(i), p.x.f and the same forms on the left of = read and assign properties. obj.method(args) and method(obj, args) call a method, and a class method wins over current-folder and path functions and builtins of that name (imported, local and private functions of the calling file come first, as in MATLAB); [a, b] = obj.method() takes several outputs, also when obj is an expression (s.p.method(), c{1}.method(), method(Pt(3)), method(make())), evaluated once. Inside a method, nargin and nargout count obj. Name.method(args) calls a Static method and Name.Const reads a Constant property.
Handle classes: classdef Name < handle makes a class whose objects carry identity. b = a copies the reference, so b.x = 1 changes a.x too, and a method changes the object without returning it (function move(obj, d) obj.x = obj.x + d; end, called as h.move(1)). a == b and a ~= b (eq, ne) compare identity; isequal(a, b) is true for the same object and for two objects of one class whose properties are all equal. delete(h) (or h.delete()) runs the class's delete method, then those of its superclasses, and invalidates every copy: isvalid(h) is then false, any property use errors "Invalid or deleted object." and the display reads "handle to deleted Name". An error inside a delete method becomes a warning and the object is deleted anyway. A delete method declared in methods (Access = private) can be called only by the class's own methods (protected: also by subclass methods); from elsewhere delete(h) and h.delete() both error "Cannot access private method 'delete' of class 'Name'." When the last reference to a handle object goes (cleared, overwritten, never stored), the object is freed silently at a statement boundary, reference cycles included; its delete method runs only on an explicit delete. isa(h, 'handle') is true; handle itself cannot be constructed. methods lists delete, eq, isvalid and ne for a handle class. A subclass of a handle class is a handle class.
Inheritance: classdef B < A, or classdef C < A & B for several superclasses (their class files in the same folder). The subclass has every property and method of its superclasses; its own properties come first in displays and listings, then each superclass's, left to right; a class reached through two superclasses (a common base) counts once. Method lookup takes the subclass's own method first, then the superclasses' in order; a method that two superclasses define differently and the subclass does not is ambiguous, and calling it errors "Method 'm' of class 'C' is ambiguous: the superclasses 'A' and 'B' both define it; define m in C to choose." (MATLAB rejects such a class when it is loaded; here the other methods stay usable). In a constructor, obj = obj@A(args) calls A's constructor on the object being built (for a handle class obj@A(args); alone is enough); superclasses whose constructor is not called that way get an implicit call without arguments first, left to right. In a method, m@A(obj, args) calls A's version of m (any method of the subclass may call it). Protected members can be used in the class and its subclasses; private ones only in the defining class, even on a subclass object. isa(obj, 'A') is true up the chain, superclasses(obj) or superclasses('Name') lists every superclass (depth first, left to right, handle last), and methods, properties and fieldnames include inherited members. A class cannot derive from both handle and value classes; a Sealed class cannot be subclassed ("class 'A' is Sealed and cannot be subclassed"); a superclass that is missing, not a class file, or the class itself (directly or through others) is an error naming the file and line. methods (Abstract) lists method signatures without bodies (r = area(obj), [a, b] = f(obj, x), or name); a class with an abstract method it does not implement, declared or inherited, cannot be constructed: "Cannot create an object of the abstract class 'Shape': it does not implement the abstract methods area." A subclass implementing them can.
Property get and set methods: function v = get.x(obj) runs for every read of obj.x and function obj = set.x(obj, v) for every assignment to it (in a handle class the set method needs no output), from outside and from other methods alike, the constructor included (defaults are stored without it); obj.x(i) = v reads through the get method, changes the value and passes it to the set method. Inside get.x and set.x themselves, obj.x reads and writes the stored value without calling them again. A set method of a value class must return the object. A Dependent property has no stored value: reading it needs a get method ("In class 'C', no get method is defined for Dependent property 'x'. A Dependent property needs a get method to access its value.") and assigning it a set method (the same text with set), which usually stores other properties; displays show its get value. get and set methods are written in a methods block without attributes, only for properties of the same class.
Other attributes: SetAccess = immutable properties can be set only by the defining class's constructor (not by methods it calls) and read as GetAccess says ("Cannot set immutable property 'id' of class 'B' outside the constructor of 'B'."); Hidden properties work as usual but are not listed by properties and fieldnames or shown by the display; Transient is accepted and has no effect until objects can be saved.
Private and protected members, a constructor declared in methods (Access = private) included, can be used only inside the class's methods (protected: also in subclasses); outside access fails with "Cannot access private property 'k' of class 'Pt'." and similar messages. A Constant property cannot be set. An unknown name gives "Unrecognized method, property, or field 'y' for class 'Pt'." (assignment: "Unrecognized property 'y' for class 'Pt'.").
Without a semicolon an object displays like this (loose format):
p =Pt with properties: x: 3
label: 'a'
Origin: 0The public properties appear in declaration order, Constant ones included, formatted like struct fields: the names are right-aligned, as struct display does here (MATLAB's class display left-aligns them). disp(p) prints the text from the "Pt with properties:" line on. A class without public properties shows " Pt with no properties.". A method named disp replaces the text, also when it is private: p = ... then prints the "p =" line, a blank line and what the method prints.
class(p) is 'Pt'; isa, isobject, properties, methods, isprop, ismethod, fieldnames (the public properties), isequal (same class and equal properties) and whos (Class column Pt) know the class. isstruct(p) is false. struct(p) returns every stored property, private ones included, as a struct and prints a one-line warning. An object has no struct fields: numfields(p) is 0, isfield(p, name) is false, getfield(p, 'x') and setfield(p, 'x', v) follow the property rules above (a private property or a Constant one fails as p.x does), and rmfield, orderfields and struct2cell are not defined for it. subsref(p, substruct('.', 'x')) and p = subsasgn(p, substruct('.', 'x'), v) read and assign like p.x and p.x = v, with the same rules; a '()' step after a method name passes its arguments (subsref(p, substruct('.', 'shift', '()', {1}))). subsasgn is available for these objects only.
Class folders: a folder named @Name directly inside the current folder, a search path folder or a package folder (+pkg/@Name is the class pkg.Name) holds the class file Name.m and, each in its own file, further methods: every other function file @Name/method.m is a method of the class, called as method(obj, ...) or obj.method(...), found before current-folder and path functions and builtins of that name when the first argument is an object of the class (an imported, local or private function of that name still comes first; obj.method(...) always calls the method), inherited by subclasses and listed by methods and ismethod. Such a method is public and not Static unless a methods block of the class file declares its signature without a body (r = method(obj, x) in methods (Static) or methods (Access = private)); a declaration without a body is accepted only in a class folder. The constructor and the get/set methods stay in the class file; a method defined both there and in its own file is an error naming both files. A folder @Name/private is visible to the class file and to the method files. Folders are searched in lookup order (current folder, then the path): when one folder holds both Name.m and @Name/Name.m the class folder wins, and otherwise the first folder with either wins, so a plain Name.m of the current folder comes before a class folder on the path. An object keeps its class: a later import of a class with the same name changes what Name(...) constructs, not the methods of existing objects. genpath leaves @ folders off the path. Method files are read when first called; a new or edited one is used from the next run. Old-style class folders, where @Name/Name.m is a function calling class(s, 'Name'), are not supported: Name(...) errors "Old-style @Name class folders (class() constructors) are not supported; use a classdef file."
Editing a class file takes effect on the next run, also for objects made earlier; inside one run the definition first loaded stays.
Example
iskeyword('classdef') % trueDifferences from MATLAB: Behaviour follows the MATLAB documentation; GNU Octave 10.3 confirms handle aliasing, isequal on handles, superclass constructor and method calls, protected access and get/set methods, and where it differs (Octave has no isvalid, superclasses or handle ==, resolves ambiguous inherited methods to the first superclass, runs delete methods when an object is freed and leaves an object usable after delete(obj) inside its own class) the documentation wins. Not supported yet (each reports an error naming the file and line): property listeners (SetObservable, GetObservable), and class attributes other than Sealed. Also not supported yet: overloading operators and functions other than disp (plus, eq, subsref, subsasgn, size, numel methods), object arrays ([a b], a(2)), old-style @folder classes, @folder methods for built-in classes (@double/f.m) and saving objects (save reports "objects of class 'Pt' cannot be saved yet"). A handle object's delete method does not run when the object is freed implicitly. A classdef typed in the console or in a script is rejected as before. With several outputs, a method named like a function or builtin wins for name(expr, ...) only when expr is a variable, a path into one (s.p, c{1}) or a constructor call; for another expression, such as a function's result, the function or builtin runs.
These are the engine’s help pages. Each page keeps its compatibility notes. File operations are unavailable in the browser.