MATLAB Object-Oriented Programming

(Joyce) #1
Add Properties

The LineGraph class implements the interface defined in the GraphInterface class
and adds two additional properties—LineColor and LineType. This class defines initial
values for each property, so specifying property values in the constructor is optional. You
can create a LineGraph object with no data, but you cannot produce a graph from that
object.

properties
LineColor = [0 0 0];
LineType = '-';
end

The LineGraph Constructor

The constructor accepts a struct with x and y coordinate data, and property name/
property value pairs:

function gobj = LineGraph(data,varargin)
if nargin > 0
gobj.Data = data;
if nargin > 2
for k=1:2:length(varargin)
gobj.(varargin{k}) = varargin{k+1};
end
end
end
end

Implement the draw Method

The LineGraph draw method uses property values to create a line object. The
LineGraph class stores the line handle as protected class data. To support the use of no
input arguments for the class constructor, draw checks the Data property to determine if
it is empty before proceeding:

function gobj = draw(gobj)
if isempty(gobj.Data)
error('The LineGraph object contains no data')
end
h = line(gobj.Data.x,gobj.Data.y,...
'Color',gobj.LineColor,...
'LineStyle',gobj.LineType);
gobj.Primitive = h;

12 How to Build on Other Classes

Free download pdf