Representative Class Code

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
end
properties (Constant)
P = pi
end
properties (Dependent)
Area
end
methods
function obj = CircleArea(r)
if nargin > 0
end
end
function val = get.Area(obj)
end
if val < 0
end
end
function plot(obj)
d = r*2;
pos = [0 0 d d];
curv = [1 1];
rectangle('Position',pos,'Curvature',curv,...
'FaceColor',[.9 .9 .9])
line([0,r],[r,r])
text(r/2,r+.5,['r = ',num2str(r)])
title(['Area = ',num2str(obj.Area)])
axis equal
end
function disp(obj)
end
end
methods (Static)
function obj = createObj
obj = CircleArea(r);
end
end
end

Use the CircleArea Class

Create an object using the dialog box:

ca = CircleArea.createObj

Query the area of the defined circle:

ca.Area
ans =

164.2202