MATLAB Object-Oriented Programming

(Joyce) #1

Description of Class Definition


Class definition code begins with the classdef keyword followed by the class name:
classdef CircleArea
Define the Radius property within the properties-end keywords. Use default
attributes:
properties
Radius
end
Define the P property as Constant (“Define Class Properties with Constant Values” on
page 15-2). Call the pi function only once when class is initialized.
properties (Constant)
P = pi
end
Define the Area property as Dependent because its value depends on the Radius
property.
properties (Dependent)
Area
end
methods % Begin defining methods
The CircleArea class constructor method has the same name as the class and accepts
the value of the circle radius as an argument. This method also allows no input
arguments. (“Class Constructor Methods” on page 9-21)
function obj = CircleArea(r)
if nargin > 0
obj.Radius = r;
else
obj.Radius = 0;
end
end
Because the Area property is Dependent, it does not store its value. The get.Area
method calculates the value of the Area property whenever it is queried. (“Set and Get
Methods for Dependent Properties” on page 8-62)
function val = get.Area(obj)
val = obj.P*obj.Radius^2;
end

Representative Class Code
Free download pdf