MATLAB Object-Oriented Programming

(Joyce) #1
The set.Radius method tests the value assigned to the Radius property to ensure the
value is not less than zero. MATLAB calls set.Radius to assign a value to Radius.
(“Property Set Methods” on page 8-56.
function obj = set.Radius(obj,val)
if val < 0
error('Radius must be positive')
end
obj.Radius = val;
end
The CircleArea class overloads the plot function. The plot method uses the
rectangle function to create a circle and draws the radius. (“Overload Functions in
Class Definitions” on page 9-34
function plot(obj)
r = obj.Radius;
d = r*2;
pos = [0 0 d d];
curv = [1 1];
rectangle('Position',pos,'Curvature',curv)
line([0,r],[r,r])
text(r/2,r+.5,['r = ',num2str(r)])
axis equal
end
The CircleArea class overloads the disp function to change the way MATLAB displays
objects in the command window.
function disp(obj)
rad = obj.Radius;
disp(['Circle with radius: ',num2str(rad)])
end
end
methods (Static)
The CircleArea class defines a Static method that uses a dialog box to create an
object. (“Static Methods” on page 9-32
function obj = createObj
prompt = {'Enter the Radius'};
dlgTitle = 'Radius';
rad = inputdlg(prompt,dlgTitle);
r = str2double(rad{:});
obj = CircleArea(r);
end

5 Class Definition—Syntax Reference

Free download pdf