Class design enable you to pass a subclass object to a superclass method and have the method execute properly. At the same time, subclass methods can apply special processing to the unique aspects of the subclass. Some useful techniques include:
Extend — Calling a superclass method from within a subclass method
Redefine — Reimplementing in the subclass, the protected methods that are called from within a public superclass method
Override — Defining the same named methods in both super and subclass, but using different implementations
Subclass methods can call superclass methods of the same name. This technique enables you to extend a superclass method in a subclass without completely redefining the superclass method.
For example, suppose that both superclass and subclass define
a method called
foo. The method names are the same
so the subclass method can call the superclass method. However, the
subclass method can also perform other steps before and after the
call to the superclass method. It can operate on the specialized parts
to the subclass that are not part of the superclass.
For example, this subclass defines a
that calls the superclass
classdef Sub < Super methods function foo(obj) % preprocessing steps ... foo@Super(obj); % postprocessing steps ... end end end
A superclass method can define a process that executes in a
series of steps using a protected method for each step (
protected). Then, subclasses can create
their own versions of the protected methods that implement the individual
steps in the process.
Implement this technique as shown here:
classdef Super methods function foo(obj) step1(obj) % Call step1 step2(obj) % Call step2 step3(obj) % Call step3 end end methods (Access = protected) function step1(obj) % Superclass version end function step2(obj) % Superclass version end function step3(obj) % Superclass version end end end
The subclass does not reimplement the
it reimplements only the methods that carry out the series of steps
That is, the subclass can specialize the actions taken by each step,
but does not control the order of the steps in the process. When you
pass a subclass object to the superclass
foo method, MATLAB® calls
the subclass step methods because of the dispatching rules.
classdef Sub < Super ... methods (Access = protected) function step1(obj) % Subclass version end function step2(obj) % Subclass version end function step3(obj) % Subclass version end ... end end
You can completely redefine a superclass method in a subclass. In this case, both the superclass and the subclass would define a method with the same name. However, the implementation would be different and the subclass method would not call the superclass method.
classdef Super methods function foo(obj) % Superclass implementation end end end
classdef Sub < Super methods function foo(obj) % Subclass implementation end end end