例として、 という抽象クラスと という 2 つのサブクラスを作成し、両方Shape
がという (抽象) メソッドを実装しているとします。多数のandオブジェクトを作成し、それらを配列に格納し、配列を反復処理して各配列オブジェクトを呼び出すことができるようにしたいと考えています。Circle
Rectangle
Draw
Circle
Rectangle
Draw
私は次のようなことを試しました:
形状.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
長方形.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
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();