MATLAB Object-Oriented Programming

(Joyce) #1

Call Only Direct Superclass from Constructor


Call only direct superclass constructors from a subclass constructor. For example,
suppose class B derives from class A and class C derives from class B. The constructor for
class C cannot call the constructor for class A to initialize properties. Class B must
initialize class A properties.

The following implementations of classes A, B, and C show how to design this relationship
in each class.

Class A defines properties x and y, but assigns a value only to x:

classdef A
properties
x
y
end
methods
function obj = A(x)
...
obj.x = x;
end
end
end

Class B inherits properties x and y from class A. The class B constructor calls the class A
constructor to initialize x and then assigns a value to y.

classdef B < A
methods
function obj = B(x,y)
...
obj@A(x);
obj.y = y;
end
end
end

Class C accepts values for the properties x and y, and passes these values to the class B
constructor, which in turn calls the class A constructor:

classdef C < B
methods
function obj = C(x,y)

12 How to Build on Other Classes

Free download pdf