Main Content

Subclass Syntax

Subclass Definition Syntax

To define a class that is a subclass of another class, add the superclass to the classdef line after a < character:

classdef ClassName < SuperClass

When inheriting from multiple classes, use the & character to indicate the combination of the superclasses:

classdef ClassName < SuperClass1 & SuperClass2

See Class Member Compatibility for more information on deriving from multiple superclasses.

Class Attributes

Subclasses do not inherit superclass attributes.

Subclass double

Suppose you want to define a class that derived from double and restricts values to be positive numbers. The PositiveDouble class:

classdef PositiveDouble < double
   methods
      function obj = PositiveDouble(data)
         if nargin == 0
            data = 1;
         else
            mustBePositive(data)
         end
         obj = obj@double(data);
      end
   end
end

Create an object of the PositiveDouble class using a 1-by-5 array of numbers:

a = PositiveDouble(1:5);

You can perform operations on objects of this class like any double.

sum(a)
ans =

    15

Objects of the PositiveDouble class must be positive values.

a = PositiveDouble(0:5);
Error using mustBePositive (line 19)
Value must be positive.

Error in PositiveDouble (line 7)
            mustBePositive(data)

Related Topics