Class
Define Class
classdef Num < handle
properties
value
end
methods
% Constructor
function self = Num(n)
self.value = n;
end
% Accessor
function disp(self)
fprintf('Num: %d\n', self.value);
end
% Mutator
function add(self, v)
self.value = self.value + v;
end
function multiply(self, v)
self.value = self.value*v;
end
end
end
function numTest()
% Create a Num Object
n = Num(1);
% Access Properties
n.value %1
n.value = 10; %10
n.disp(); %Num: 10
% Access Mutators
n.add(10); %20
n.disp(); %Num: 20
n.multiply(10); %200
n.disp; %Num: 200
% Access object
disp(n); %Num: 200
add(n, 10);
disp(n); %Num: 210
multiply(n, 10);
disp(n); %Num: 2100
end
- Each class has only one constructor, extra constructors cause errors
- Class in MATLAB is more like struct in C/C++, use obj.property to access properties directly, not need get and set functions
classdef Num
properties
value
end
methods
% Constructor
function self = Num(n)
self.value = n;
end
% Accessor
function disp(self)
fprintf('Num: %d\n', self.value);
end
% Mutator
function self = add(self, v)
self.value = self.value + v;
end
function self = multiply(self, v)
self.value = self.value*v;
end
end
end
function numTest()
% Create a Num Object
n = Num(10);
% Access Mutators
n = n.add(10); %20
n.disp(); %Num: 20
n = n.multiply(10); %200
n.disp; %Num: 200
n = add(n, 10);
n.disp(); %Num: 210
n = multiply(n, 10);
n.disp(); %Num: 2100
end
n = n.add(10) or n = add(n, 100) to update the property of object n, if class is not derived from handle
Destructor
classdef Num < handle
properties
value
end
methods
% Constructor
function self = Num(n)
self.value = n;
end
% Accessor
function disp(self)
fprintf('Num: %d\n', self.value);
end
function delete(self)
fprintf('Destructor is called ...\n');
end
end
end