As an example, suppose I have created an abstract class called Shape
and two subclasses called Circle
and Rectangle
that both implement an (abstract) method called Draw
. I would like to be able to create a number of Circle
and Rectangle
objects, store them in an array and call Draw
on each array object by iterating through the array.
I have tried something like the following:
Shape.m:
classdef (Abstract) Shape < handle
methods (Abstract)
Draw(obj);
end
end
Circle.m:
classdef Circle < Shape
methods
function obj = Draw(obj)
disp('This is a circle');
end
end
end
Rectangle.m:
classdef Rectangle < Shape
methods
function obj = Draw(obj)
disp('This is a rectangle');
end
end
end
test.m:
shapes = Shape.empty();
myrect = Rectangle();
mycirc = Circle();
shapes(end + 1) = myrect;
shapes(end + 1) = mycirc;
for i = 1:size(shapes,1)
shapes(i).Draw();
end
When I try to run test.m, I get the following error message:
Error using Shape.empty
Abstract classes cannot be instantiated.
Class 'Shape' defines abstract methods
and/or properties.
Error in test (line 1)
shapes = Shape.empty();