Objektorientierung in MATLAB

Die objektorientierte Programmierung in MATLAB ist möglich. Bitte lesen Sie sich dazu die Dokumentation durch (doc classdef).

Für weitere Fragen oder als kleinen Vorgeschmack anbei zwei beispielhafte Klassendefinitionen. Klasse A enthält verschiedene Attribute mit verschiendenen Zugriffsrechten. Außerdem ist ein Singleton-Pattern hinterlegt (siehe Singleton-Pattern):

% (C) 2012, Datenverarbeitung in der Konstruktion, TU Darmstadt
%
% Author: André Picard
% Date: 22.11.2012
% Version: 1.0
%

classdef ClassA

properties
AttrA;
AttrB = 10;
end

properties (SetAccess = private, GetAccess = private) % See Table of Property Attributes
AttrC = 'Private';
end
properties (Access = protected)
AttrD = 'Protected';
end

methods
% Constructor
function obj = ClassA(varargin)
% Default contructor
if nargin == 0
fprintf('Default constructor of "%s". ', mfilename);
return
end

% Specific constructor
fprintf('Specific constructor of "%s". ', mfilename);
obj.AttrA = varargin{1};
obj.('AttrB') = 20; % Find Attribute by name
end

% Getter and Setter
function value = get.AttrA(obj)
value = obj.AttrA;
end
function obj = set.AttrA(obj, value)
obj.AttrA = value;
end

% Default methods
function disp(obj)
fprintf('Format your output here. ');
end

% Other methods
function toString(obj)
fprintf('I am called within "%s". ', mfilename);
end
end

methods (Static)
function value = getInstance(num)
if numel(num) ~= 1 || ~isnumeric(num) || mod(num, 1) ~= 0 || num <= 0
error('Input parameter must be a positive integer')
end

persistent instances;
if isempty(instances)
instances = {};
end
if numel(instances) < num
instances{num} = ClassA(num);
end
value = instances{num};
end
end
end

 

% (C) 2012, Datenverarbeitung in der Konstruktion, TU Darmstadt

% Author: André Picard
% Date: 22.11.2012
% Version: 1.0
%

classdef ClassB < ClassA

methods
% Constructor
function obj = ClassB(value)
obj = obj@ClassA(value); % Caution: Otherweise calling the default constructor of "ClassA".
fprintf('Specific constructor of "%s". ', mfilename);
end


function toString(obj)
toString@ClassA(obj)
fprintf('I am called within "%s". ', mfilename);
end

function testAccess(obj)
fprintf('Access to private variable: %s ', obj.AttrC);
fprintf('Access to protected variable: %s ', obj.AttrD);
end
end

methods (Access = private)
function methodB(obj)
fprintf('I am a private method within "%s". ', mfilename);
end
end
end