All class methods must be defined within
methods blocks. An exception
to this rule is described at the end of this subsection. Those
blocks can have additional attributes specifying the access rights or whether
the methods are static, i.e., methods that can be called without creating an
object of that class.
classdef some_class methods function obj = some_class () disp ("New instance created."); endfunction function disp (obj) disp ("Here is some_class."); endfunction endmethods methods (Access = mode) function r = func (obj, r) r = 2 * r; endfunction endmethods methods (Static = true) function c = circumference (radius) c = 2 * pi () .* radius; endfunction endmethods endclassdef
The constructor of the class is declared in the
methods block and must
have the same name as the class and exactly one output argument which is an
object of its class.
It is also possible to overload built-in or inherited methods, like the
disp function in the example above to tell Octave how objects of
some_class should be displayed (see Class Methods).
In general, the first argument in a method definition is always the object that
it is called from. Class methods can either be called by passing the object as
the first argument to that method or by calling the object followed by a dot
.") and the method’s name with subsequent arguments:
>> obj = some_class (); New instance created. >> disp (obj); # both are >> obj.disp (); # equal
some_class, the method
func is defined within a
block setting the
Access attribute to mode, which is one of:
The methods can be accessed from everywhere.
The methods can only be accessed from other class methods. Subclasses of that class cannot access them.
The methods can only be accessed from other class methods and from subclasses of that class.
The default access for methods is
Finally, the method
circumference is defined in a static
block and can be used without creating an object of
some_class. This is
useful for methods, that do not depend on any class properties. The class name
and the name of the static method, separated by a dot ("
."), call this
static method. In contrast to non-static methods, the object is not passed as
first argument even if called using an object of
>> some_class.circumference (3) ⇒ ans = 18.850 >> obj = some_class (); New instance created. >> obj.circumference (3) ⇒ ans = 18.850
Additionally, class methods can be defined as functions in a folder of the same
name as the class prepended with the ‘@’ symbol
(see Creating a Class). The main
classdef file has to be stored in
this class folder as well.