Calling Superclass Methods on Subclass Objects

Calling a Superclass Constructor

If you create a subclass object, MATLAB® calls the superclass constructor to initialize the superclass part of the subclass object. By default, MATLAB calls the superclass constructor without arguments. If you want the superclass constructor called with specific arguments, explicitly call the superclass constructor from the subclass constructor. The call to the superclass constructor must come before any other references to the object.

The syntax for calling the superclass constructor uses an @ symbol:

classdef MySub < MySuperClass
   methods
      function obj = MySub(arg1,arg2,...)
         obj = obj@MySuperClass(SuperClassArguments);
            ...
      end % MySub
   end % methods
end % classdef

Interpret this syntax as meaning, the MySub object arrives at the MySuperClass constructor , which constructs the MySuperClass part of the object using the specified arguments.

See Constructing Subclasses for more information.

Calling Superclass Methods

You can call a superclass method from a subclass method if both methods have the same name. From the subclass, reference the method name and superclass name with the @ symbol. See Modifying Superclass Methods for more information on when to call superclass methods.

For example, a subclass can call a superclass disp method to implement the display of the superclass part of the object, and then add code to display the subclass part:

classdef MySub < MySuperClass 
   methods
      function disp(obj)
         disp@MySuperClass(obj)
            ...
      end % disp
   end % methods
end % classdef

This diagram illustrates how to call the superMethod defined at MySuperClass.

Was this topic helpful?