例如,假设我创建了一个名为的抽象类Shape
和两个名为的子类Circle
,Rectangle
它们都实现了一个名为Draw
. 我希望能够创建多个Circle
和Rectangle
对象,将它们存储在一个数组中,并Draw
通过遍历数组来调用每个数组对象。
我尝试过类似以下的方法:
形状.m:
classdef (Abstract) Shape < handle
methods (Abstract)
Draw(obj);
end
end
圆.m:
classdef Circle < Shape
methods
function obj = Draw(obj)
disp('This is a circle');
end
end
end
矩形.m:
classdef Rectangle < Shape
methods
function obj = Draw(obj)
disp('This is a rectangle');
end
end
end
测试.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
当我尝试运行 test.m 时,我收到以下错误消息:
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();