Documentation

This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English verison of the page.

Note: This page has been translated by MathWorks. Please click here
To view all translated materals including this page, select Japan from the country navigator on the bottom of this page.

Call Superclass Methods on Subclass Objects

Superclass Relation to Subclass

Subclasses can override superclass methods to support the greater specialization defined by the subclass. Because of the relationship that a subclass object is a superclass object, it is often useful to call the superclass version of the method before executing the specialized subclass code.

How to Call Superclass Methods

Subclass methods can call superclass methods if both methods have the same name. From the subclass, reference the method name and superclass name with the @ symbol.

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

For example, a subclass can call a superclass disp method to implement the display of the superclass part of the object. Then the subclass adds code to display the subclass part of the object:

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

How to Call 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:

In the following class, the MySub object is initialized by the MySuperClass constructor. The superclass constructor constructs the MySuperClass part of the object using the specified arguments.

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

See Subclass Constructors for more information.

Related Examples

Was this topic helpful?