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.
Subclasses do not inherit superclass attributes.
Suppose you want to define a class that derived from double
and restricts values to be positive numbers. The PositiveDouble
class:
Supports a default constructor (no input arguments). See No Input Argument Constructor Requirement
Restricts the inputs to positive values using mustBePositive
.
Calls the superclass constructor with the input value to create the double numeric value.
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)