1.定义一个Superclass类
classdef Superclass
properties
prop1
prop2
end
methods
function obj = Superclass(val1, val2)
if nargin == 2
obj.prop1 = val1;
obj.prop2 = val2;
end
end
end
end
2.定义一个MySubclass类,从Superclass类继承
classdef MySubclass < Superclass
properties
prop3
end
methods
function obj = MySubclass(val1,val2,val3)
if nargin ~= 3
prop1 = []
prop2 = []
prop3 = []
end
obj@Superclass(val1, val2);
obj.prop3 = val3;
end
end
end
注意这里**obj@Superclass(val1, val2)**语句的含义
3.定义一个Rectangle类
classdef Rectangle
properties
len = 0;
width = 0;
end
methods
function obj = Rectangle(l,w)
if nargin == 2
obj.len = l;
obj.width = w;
end
end
function outarg = rectarea(obj)
outarg = obj.len*obj.width;
end
function out = lt(obj1, obj2)
out = lt(rectarea(obj1), rectarea(obj2));
end
function out = gt(obj1, obj2)
if isa(obj2, 'Rectangle')
out = gt(rectarea(obj1), rectarea(obj2));
else
% 1.out = gt(rectarea(obj1), 20);
inp2 = Rectangle(obj2, 1);
out = get(obj1, inp2);
end
end
function disp(obj)
fprintf('The rectangle has length %.2f and withd %.2f. \n', obj.len, obj. width);
end
end
end
4.定义一个Box类,从Rectangle类继承
classdef Box < Rectangle
%UNTITLED18 此处显示有关此类的摘要
% 此处显示详细说明
properties
height=0;
end
methods
function obj = Box(l, w, h)
obj@Rectangle(l, w);
obj.height =h;
end
% Rectangle methods也被继承
function out = calvol(obj)
out = obj.rectarea*obj.height;
end
function disp(obj)
fprintf('The box has length %.2f, withd %.2f and height %.2f. \n', obj.len, obj. width, obj.height);
end
end
end