Subclassing and Inheritance

Subclassing allows you to build component models based on other component models by extension. Subclassing applies only to component models, not domain models. The syntax for subclassing is based on the MATLAB® class system syntax for subclassing using the < symbol on the declaration line of the component model:

component MyExtendedComponent < PackageName.MyBaseComponent
  % component implementation here
end

By subclassing, the subclass inherits all of the members (parameters, variables, nodes, inputs and outputs) from the base class and can add members of its own. When using the subclass as an external client, all public members of the base class are available. All public and protected members of the base class are available to the events, equation, structure, and other sections of the subclass. The subclass may not declare a member with the same identifier as a public or protected member of the base class.

The setup function of the base class is executed before the setup function of the subclass.

Note

  • Starting in R2019a, using setup is not recommended. Other constructs available in Simscape™ language let you achieve the same results without compromising run-time capabilities. For more information, see setup is not recommended.

The equations of both the subclass and the base class are included in the overall system of equations.

For example, you can create the base class ElectricalBranch.ssc, which defines an electrical branch with positive and negative external nodes, initial current and voltage, and relationship between the component variables and nodes (and therefore, connects the component variables with the Through and Across domain variables). Such a component is not very useful as a library block, so if you do not want the base class to appear as a block in a custom library, set the Hidden=true attribute value:

component (Hidden=true) ElectricalBranch
  nodes
    p = foundation.electrical.electrical; % +:left
    n = foundation.electrical.electrical; % +:right
  end
  variables
    i = { 0, 'A' };
    v = { 0, 'V' };
  end
  branches
    i : p.i -> n.i;
  end
  equations
    v == p.v - n.v;
  end
end

If, for example, your base class resides in a package named +MyElectrical, then you can define the subclass component Capacitor.ssc as follows:

component Capacitor < MyElectrical.ElectricalBranch
% Ideal Capacitor
  parameters
    c = { 1, 'F' };
  end
  equations
      assert(c>0, 'Capacitance must be greater than zero');	
      i == c * v.der;
  end
end

The subclass component inherits the p and n nodes, the i and v variables with initial values, and the relationship between the component and domain variables from the base class. This way, the Capacitor.ssc file contains only parameters and equations specific to the capacitor.