MATLAB Object-Oriented Programming

(Joyce) #1

Representative Class Code


In this section...
“Class Calculates Area” on page 5-28
“Description of Class Definition” on page 5-31

Class Calculates Area


The CircleArea class shows the syntax of a typical class definition. This class stores a
value for the radius of a circle and calculates the area of the circle when you request this
information. CircleArea also implements methods to graph, display, and create objects
of the class.

To use the CircleArea class, copy this code into a file named CircleArea.m and save
this file in a folder that is on the MATLAB path.

classdef CircleArea
properties
Radius
end
properties (Constant)
P = pi
end
properties (Dependent)
Area
end
methods
function obj = CircleArea(r)
if nargin > 0
obj.Radius = r;
end
end
function val = get.Area(obj)
val = obj.P*obj.Radius^2;
end
function obj = set.Radius(obj,val)
if val < 0
error('Radius must be positive')
end
obj.Radius = val;
end

5 Class Definition—Syntax Reference

Free download pdf