One of the major benefits of object-orientation is the ability to extend the behavior and properties of an existing class. The original class, known as the base class, is extended to create a more specialized version of that class, known as the derived class. In this process, the data and behavior of the original class in the form of variable declarations, equations, and certain other contents are reused, or inherited, by the derived class. In fact, the inherited contents is copied from the superclass into the derived class, but before copying certain operations, such as type expansion, checking, and modification, are performed on the inherited contents when appropriate. This chapter describes the inheritance concept in Modelica, together with the related concepts modification and redeclaration.
The class A is called a base class of B, if B extends A. The converse relation is then expressed as B being a derived class of A, or as B being derived from A. This relation is specified by an extends-clause in B or in one of B’s base classes. A class inherits all elements from its base classes, and may modify all non-final elements inherited from base classes, as explained below.
The extends-clause is used to specify inheritance from a base class into an (enclosing) class containing the extends-clause. It is an unnamed element of a class definition that uses a name and an optional modification to specify a base class of the class defined using the class definition. The syntax of the extends-clause is as follows:
The name of the base class is looked up in the partially flattened enclosing class (section 5.2) of the extends-clause. If the optional class-or-inheritance-modification contains any inheritance-modification the base class is then modified as described in section 7.4. The possibly modified found base class is flattened with a new environment and the partially flattened enclosing class of the extends-clause. The new environment is the result of merging
arguments of all enclosing class environments that match names in the flattened base class
a class-modification constructed from all argument of the inheritance-modification
in that order.
The elements of the flattened base class become elements of the flattened enclosing class, and are added at the place of the extends-clause: specifically components and classes, the equation sections, algorithm sections, optional external-clause, and the contents of the annotation at the end of the class, but excluding import-clauses.
[From the example above we get the following flattened class:
The ordering of the merging rules ensures that, given classes A and B defined above,
yields an instance with bcomp.b = 3, which overrides b = 2.]
The declaration elements of the flattened base class shall either:
Not already exist in the partially flattened enclosing class (i.e., have different names).
The new element is a long form of redeclare or uses the class extends A syntax, see section 7.3.
Be exactly identical to any element of the flattened enclosing class with the same name and the same level of protection (public or protected) and same contents. In this case, the first element in order (can be either inherited or local) is kept. It is recommended to give a warning for this case; unless it can be guaranteed that the identical contents will behave in the same way.
Otherwise the model is incorrect.
Equations of the flattened base class that are syntactically equivalent to equations in the flattened enclosing class are discarded. This feature is deprecated, and it is recommended to give a warning when discarding them and for the future give a warning about all forms of equivalent equations due to inheritance.
[Equations that are mathematically equivalent but not syntactically equivalent are not discarded, hence yield an overdetermined system of equations.]
Multiple inheritance is possible since multiple extends-clauses can be present in a class.
[As stated in section 126.96.36.199, it is illegal for an extends-clause to influence the lookup of the class name of any extends-clause in the same class definition.]
If an extends-clause is used under the protected heading, all elements of the base class become protected elements of the current class. If an extends-clause is a public element, all elements of the base class are inherited with their own protection. The eventual headings protected and public from the base class do not affect the consequent elements of the current class (i.e., headings protected and public are not inherited).
Since specialized classes of different kinds have different properties, see section 4.6, only specialized classes that are in some sense compatible to each other can be derived from each other via inheritance. The following table shows which kind of specialized class can be used in an extends-clause of another kind of specialized class (the grey cells mark the few exceptional cases, where a specialized class can be derived from a specialized class of another kind):
If a derived class is inherited from another type of specialized class, then the result is a specialized class of the derived class type.
[For example, if a block inherits from a record, then the result is a block.]
All specialized classes can be derived from class, provided that the resulting class fulfills the restriction of the specialized class. A class may only contain class definitions, annotations, and extends-clauses (having any other contents is deprecated).
[It is recommended to use the most specific specialized class.]
The specialized classes package, operator, function, type, record, operator record, and expandable connector can only be derived from their own kind and from class.
[E.g., a package can only be base class for packages. All other kinds of classes can use the import-clause to use the contents of a package.]
The class name used after extends for base classes and for constraining classes must use a class reference considered transitively non-replaceable, see definition in section 6.3.1. For a replaceable component declaration without constraining-clause the class must use a class reference considered transitively non-replaceable.
[The requirement to use a transitively non-replaceable name excludes the long form of redeclare, i.e., redeclare model extends M where M must be an inherited replaceable class.]
[The rule for a replaceable component declaration without constraining-clause implies that constraining classes are always transitively non-replaceable – both if explicitly given or implicitly by the declaration.]
A modification is part of an element. It modifies the instance generated by that element. A modification contains element modifications (e.g., vcc(unit = "V") = 1000) and element-redeclarations (e.g., redeclare type Voltage = Real(unit="V")).
There are three kinds of constructs in the Modelica language in which modifications can occur:
short class declarations
A modifier modifies one or more declarations from a class by changing some aspect(s) of the declarations. The most common kind of modifier just changes the default value or the start-attribute in a binding equation; the value and/or start-attribute should be compatible with the variable according to section 6.7.
An element modification overrides the declaration equation in the class used by the instance generated by the modified element.
[Example: Modifying the default start value of the altitude variable:
A modification (e.g., C1 c1(x = 5)) is called a modification equation, if the modified variable (here: c1.x) is a non-parameter variable.
[The modification equation is created, if the modified component (here: c1) is also created (see section 4.5). In most cases a modification equation for a non-parameter variable requires that the variable was declared with a declaration equation, see section 4.7; in those cases the declaration equation is replaced by the modification equation.]
A more dramatic change is to modify the type and/or the prefixes and possibly the dimension sizes of a declared element. This kind of modification is called an element-redeclaration (section 7.3) and requires the special keyword redeclare to be used in the modifier in order to reduce the risk for accidental modeling errors. In most cases a declaration that can be redeclared must include the prefix replaceable (section 7.3). The modifier value (and class for redeclarations) is found in the context in which the modifier occurs, see also section 5.3.1.
[Example: Scope for modifiers:
When present, the description-string of a modifier overrides the existing description.
The syntax is defined in the grammar, section A.2.5.
The modification environment of a class contains arguments which modify elements of the class (e.g., parameter changes) when the class is flattened. The modification environment is built by merging class modifications, where outer modifications override inner modifications.
[This should not be confused with inner outer prefixes described in section 5.4.]
Merging of modifiers means that outer modifiers override inner modifiers. The merging is hierarchical, and a value for an entire non-simple component overrides value modifiers for all components, and it is an error if this overrides a final prefix for a component, or if value for a simple component would override part of the value of a non-simple component. When merging modifiers each modification keeps its own each prefix.
[Example: The following larger example demonstrates several aspects:
The following example demonstrates overriding part of non-simple component:
The modification environment of the declaration of t is (x = 3). The modification environment is built by merging class modifications, as shown by:
Outer modifications override inner modifications, e.g., b = 66 overrides the nested class modification of extends C2(b = 6). This is known as merging of modifications: merge((b = 66), (b = 6)) becomes (b = 66).
A flattening of class C4 will give an object with the following variables:
Two arguments of a modification shall not modify the same element, attribute, or description-string. When using qualified names the different qualified names starting with the same identifier are merged into one modifier. If a modifier with a qualified name has the each or final prefix, that prefix is only seen as applied to the final part of the name.
The following examples are incorrect:
The following examples are correct:
The following rules apply to modifiers:
The each keyword on a modifier requires that it is applied in an array declaration/modification, and the modifier is applied individually to each element of the enclosing array (with regard to the position of each). In case of nested modifiers this implies it is applied individually to each element of each element of the enclosing array; see example. If the modified element is a vector and the modifier does not contain the each prefix, the modification is split such that the first element in the vector is applied to the first element of the vector of elements, the second to the second element, until the last element of the vector is applied to the last element of the array; it is an error if these sizes do not match. Matrices and general arrays of elements are treated by viewing those as vectors of vectors etc.
If a nested modifier is split, the split is propagated to all elements of the nested modifier, and if they are modified by the each keyword the split is inhibited for those elements. If the nested modifier that is split in this way contains re-declarations that are split, it is illegal.
This implies c[i].a[j] = j and c[i].d = i.
This implies b.c[i].a[j] = 2+j and b.c[i].d = 1+i.
This implies b[k].c[i].a[j] = j, b[k].c[i].d = i, and b[k].p = k. For c.a the additional (outer) each has no effect, but it is necessary for c.d.
Specifying array dimensions after the type works the same as specifying them after the variable name.
An element defined as final by the final prefix in an element modification or declaration cannot be modified by a modification or by a redeclaration. All elements of a final element are also final.
[Setting the value of a parameter in an experiment environment is conceptually treated as a modification. This implies that a final modification equation of a parameter cannot be changed in a simulation environment.]
[Example: Final component modification.
[Example: Final class declaration.
Modifications may contain the special keyword break instead of an expression. The intention of break is to remove the value.
The modifiers using break are merged using the same rule as other modifications, and follow the same restrictions so they cannot override a final modifier. During flattening of an instantiated model, remaining break modifications (i.e., the ones that are not further overriden) are treated as if the expression was missing. The break modifier for a variable of a simple type can be applied to the value and/or to specific attributes. Unless final was specified, it is possible to override even if no value is present, either because there was no expression originally or because break overrides another break.
[In a dialog, a tool may hide the keyword break and show an empty input field, without the overriden modification. It should also be possible to remove this modifier to restore the overriden modification.
There are also other uses of the keyword break, but importantly it is not an expression and thus it cannot be used as a sub-expression.]
[Example: Remove unwanted defaults for parameters:
Replace a given parameter value by an initial computation:
Replace the value for an inherited variable with a value computed from an algorithm:
Note that this is only legal because the modifier is modifying an inherited declaration. Due to section 4.7 it is not legal to construct the corresponding component declaration, A a(x=break);.]
A redeclare construct in a modifier replaces the declaration of a local class or component with another declaration. A redeclare construct as an element replaces the declaration of a local class or component with another declaration. Both redeclare constructs work in the same way. The redeclare construct as an element requires that the element is inherited, and cannot be combined with a modifier of the same element in the extends-clause. For modifiers, the redeclare of classes uses the short-class-definition construct, which is a special case of normal class definitions and semantically behaves as the corresponding class-definition.
A modifier with the keyword replaceable is automatically seen as being a redeclare.
In redeclarations some parts of the original declaration is automatically inherited by the new declaration. This is intended to make it easier to write declarations by not having to repeat common parts of the declarations, and does in particular apply to prefixes that must be identical. The inheritance only applies to the declaration itself and not to elements of the declaration.
The general rule is that if no prefix within one of the following groups is present in the new declaration the old prefixes of that kind are preserved.
The groups that are valid for both classes and components:
constraining type according to rules in section 7.3.2.
The groups that are only valid for components:
discrete, parameter, constant
Note that if the old declaration was a short class definition with array dimensions the array dimensions are not automatically preserved, and thus have to be repeated in the few cases they are used.
Replaceable component array declarations with array sizes on the left of the component are seen as syntactic sugar for having all arrays sizes on the right of the component; and thus can be redeclared in a consistent way.
[Note: The inheritance is from the original declaration. In most cases replaced or original does not matter. It does matter if a user redeclares a variable to be a parameter and then redeclares it without parameter.]
Example of arrays on the left of the component name:
A class declaration of the type redeclare class extends B(), where class as usual can be replaced by any other specialized class, replaces the inherited class B with another declaration that extends the inherited class where the optional class-modification is applied to the inherited class. Inherited B here means that the class containing redeclare class extends B() should also inherit another declaration of B from one of its extends-clauses. The new declaration should explicitly include redeclare.
[Since the rule about applying the optional class-modification implies that all declarations are inherited with modifications applied, there is no need to apply modifiers to the new declaration.]
For redeclare class extends B() the inherited class is subject to the same restrictions as a redeclare of the inherited element, and the original class B should be replaceable, and the new element is only replaceable if the new definition is replaceable. In contrast to normal extends it is not subject to the restriction that B should be transitively non-replaceable (since B should be replaceable).
The syntax rule for class extends construct is in the definition of the class-specifier nonterminal (see also class declarations in section 4.5):
The nonterminal class-definition is referenced in several places in the grammar, including the following case which is used in some examples below, including package extends and model extends:
[Example to extend from existing packages:
Example for an advanced type of package structuring with constraining types:
Note, since MostAir extends from PartialMedium, constant nX = 2 in package MoistAir and the model BaseProperties and the function dynamicViscosity is present in MoistAir. By the following definitions, the available BaseProperties model is replaced by another implementation which extends from the BaseProperties model that has been temporarily constructed during the extends of package MoistAir from PartialMedium. The redeclared BaseProperties model references constant nX which is 2, since by construction the redeclared BaseProperties model is in a package with nX = 2.
This definition is compact but is difficult to understand. At a first glance an alternative exists that is more straightforward and easier to understand:
Here, the usual approach is used to extend (here from PartialMedium) and in the modifier perform all redeclarations. In order to perform these redeclarations, corresponding implementations of all elements of PartialMedium have to be given under a different name, such as MoistAir2.MoistAir_BaseProperties, since the name BaseProperties already exists due to extends PartialMedium. Then it is possible in the modifier to redeclare PartialMedium.BaseProperties to MoistAir2.MoistAir_BaseProperties. Besides the drawback that the namespace is polluted by elements that have different names but the same implementation (e.g., MoistAir2.BaseProperties is identical to MoistAir2.MoistAir_BaseProperties) the whole construction does not work if arrays are present that depend on constants in PartialMedium, such as X[nX]: The problem is that MoistAir_BaseProperties extends from PartialMedium.BaseProperties where the constant nX does not yet have a value. This means that the dimension of array X is undefined and model MoistAir_BaseProperties is wrong. With this construction, all constant definitions have to be repeated whenever these constants shall be used, especially in MoistAir_BaseProperties and MoistAir_dynamicViscosity. For larger models this is not practical and therefore the only practically useful definition is the complicated construction in the previous example with redeclare model extends BaseProperties.
To detect this issue the rule on lookup of composite names (section 5.3.2) ensures that PartialMedium.dynamicViscosity is incorrect in a simulation model.]
In a replaceable declaration the optional constraining-clause defines a constraining type. Any modifications following the constraining type name are applied both for the purpose of defining the actual constraining type and they are automatically applied in the declaration and in any subsequent redeclaration. The precedence order is that declaration modifiers override constraining type modifiers.
If the constraining-clause is not present in the original declaration (i.e., the non-redeclared declaration):
The type of the declaration is also used as a constraining type.
The modifiers for subsequent redeclarations and constraining type are the modifiers on the component or short-class-definition if that is used in the original declaration, otherwise empty.
The syntax of a constraining-clause is as follows:
[Example: Merging of modifiers:
which is equivalent to defining D as
A modification of the constraining type is automatically applied in subsequent redeclarations:
A modification of the base type without a constraining type is automatically applied in subsequent redeclarations:
Circuit2 is intended to illustrate that a user can still select any resistor model (including the original one, as is done in Circuit3), since the constraining type is kept from the original declaration if not specified in the redeclare. Thus it is easy to select an advanced resistor model, without limiting the possible future changes.
A redeclaration can redefine the constraining type:
The class or type of component shall be a subtype of the constraining type. In a redeclaration of a replaceable element, the class or type of a component must be a subtype of the constraining type. The constraining type of a replaceable redeclaration must be a subtype of the constraining type of the declaration it redeclares. In an element modification of a replaceable element, the modifications are applied both to the actual type and to the constraining type.
In an element-redeclaration of a replaceable element the modifiers of the replaced constraining type are merged to both the new declaration and to the new constraining type, using the normal rules where outer modifiers override inner modifiers.
When a class is flattened as a constraining type, the flattening of its replaceable elements will use the constraining type and not the actual default types.
The number of dimension in the constraining type should correspond to the number of dimensions in the type-part. Similarly the type used in a redeclaration must have the same number of dimensions as the type of redeclared element.
In these examples the number of dimensions must be the same in T1 and T2, as well as in a redeclaration. Normally T1 and T2 are scalar types, but both could also be defined as array types (with the same number of dimensions). Thus if T2 is a scalar type (e.g., type T2 = Real) then T1 must also be a scalar type, and if T2 is defined as vector type (e.g., type T2 = Real) then T1 must also be vector type.]
Description and annotations on the constraining-clause are applied to the entire declaration, and it is an error if they also appear on the definition.
[The intent is that the description and/or annotation are at the end of the declaration, but it is not straightforward to specify this in the grammar.]
See also the examples in section 7.3.4.
The following additional constraints apply to redeclarations (after prefixes are inherited, section 7.3):
Only classes and components declared as replaceable can be redeclared with a new type, which must have an interface compatible with the constraining interface of the original declaration, and to allow further redeclarations one must use redeclare replaceable.
[Redeclaration with the same type can be used to restrict variability and/or change array dimensions.]
An element declared as constant cannot be redeclared.
An element declared as final shall not be modified, and thus not redeclared.
Modelica does not allow a protected element to be redeclared as public, or a public element to be redeclared as protected.
Array dimensions may be redeclared; provided the sub-typing rules in section 6.4 are satisfied.
[This is one example of redeclaration of non-replaceable elements.]
A declaration can have an annotation choices containing modifiers on choice, where each of them indicates a suitable redeclaration or modifications of the element. Lookup inside a choice modifier is performed in the context of the annotation, meaning that references may need to be transformed to preserve the meaning when a choice is applied in a different context.
[It is recommended to avoid expressions with references to elements that are not globally accessible, such as contents within a protected section of a class. By starting names with a dot it can be ensured that no transformation of references will be needed when a choice is applied, and that applicability of a choice does not depend on context, see section 5.3.3.]
This is a hint for users of the model, and can also be used by the user interface to suggest reasonable redeclaration, where the string comments on the choice declaration can be used as textual explanations of the choices. The annotation is not restricted to replaceable elements but can also be applied to non-replaceable elements, enumeration types, and simple variables. For a Boolean variable, a choices annotation may contain the definition checkBox = true, meaning to display a checkbox to input the values false or true in the graphical user interface.
The annotation choicesAllMatching = true on the following kinds of elements indicates that tools should automatically construct a menu with appropriate choices.
For a replaceable element the included elements should be usable for replacing it. Exact criteria for inclusion in such a menu are not defined, but there shall be a a way to at least get a selection of classes, A.B..X.Z, that are either directly or indirectly derived by inheritance from the constraining class of the declaration, where A to X are non-partial packages, and Z is non-partial.
For a record variable the included elements shall include matching record constants and calls of matching record constructors (matching classes as for replaceable elements).
This menu can be disabled using annotation choicesAllMatching = false. It is possible to combine the two annotations for one declaration, and tools may avoid generating duplicate menu entries in that case.
[When choicesAllMatching is not specified the following behavior is recommended for replaceable elements. A tool could ideally present (at least) the same choices as for choicesAllMatching = true, but if it takes (too long) time to present the list it might be better to use the choicesAllMatching = false behavior instead.]
[Example: Demonstrating the choices and choicesAllMatching = true annotations applied to replaceable elements.
[Example: Demonstrating the choicesAllMatching = true annotation for parameter records.
The choices for medium shall include Medium(), Air_30degC(), and MyAir. If Medium() is chosen it is necessary to also set its rho-parameter.]
[Example: Applying the choices annotation to nonreplaceable declarations, e.g., to describe enumerations.
The choices annotation can also be applied to Boolean variables to define a check box.
[The goal of selective model extension is to enable unforeseen structural variability without requiring deliberately prepared base-models, Bürger (2019).
This is done by deselecting specific elements from a base class, described here, combined with adding elements as normal.]
Selective model extension is activated by using one (or more) inheritance-modification in the optional class-or-inheritance-modification of an extends-clause.
[There is no corresponding mechanism for component modifications, short class definitions, or constrainedby.]
Consider a class C with an extends-clause deselecting :
The semantic rules are:
The deselection break is applied before any other, non selective model extension related, modifications of B in C.
When adding elements from B to C the elements matched by any deselection in extends B are excluded.
A component deselection, break f, matches the component with that name, f, of B and all connections with the component or its subcomponents. Matched components must be models, blocks or connectors.
A connection deselection, break connect(a, b), matches all syntactical equivalent connections of B. A connection connect(c, d), with c and d arbitrary but valid connection arguments, is syntactically equivalent to a connection deselection break connect(a, b), if, and only if, either, c is syntactically equivalent to a and d is syntactically equivalent to b or, vice versa, c is syntactically equivalent to b and d is syntactically equivalent to a. Two code fragments a and c are syntactically equivalent, if, and only if, the context-free derivations of a and c according to the grammar given in section A.2.7 are the same.
Conditionally declared components of B are assumed to be declared for all purposes of matching.
The deselection break must match at least one element of B.
The component deselection are applied before the connection deselections of the same extends-clause.
[Example: The following gives three typical use cases: adding a component on a connection, replacing a non-replaceable component, and finally constructing a reusable model from an example.
In these examples it would be possible to modify the System model instead, but in many cases that is not realistic. For instance, it may not be possible to modify the System and the controlled system may be comprised of a large number of components in System – instead of only two.]
[Some consequences of the rules are listed below:
The syntax ensures that nested components cannot be deselected.
Deselected components cannot be modified, neither in the extends-clause nor when using C. However, C may add a component with same name as a deselected component (directly or through another extends-clause) and that new component can be modified when using C.
A class using selective model extension is not necessarily a sub-type of its base class.
Deselection is designed to be light-weight in particular:
Deselection is independent of any modification.
What is deselected can be determined without considering any modifications, neither of the extending class C nor its base class B.
There is no need to instantiate any classes to know that some component is deselected (i.e., not there) for every possible instance of the model with the deselection. An instance tree is not required.
Selective model extension operates on the syntactic level only.
Conditional components can be deselected without evaluating whether they are disabled or not. In particular deselecting a disabled conditional component is not an error. Connections involving the deselected conditional component are by the deselection removed as for a disabled component.
Assuming the deselections are semantically valid they can be handled in any order. Handling component deselections before connection deselections is only necessary to semantically check that a connection deselection does not involve a deselected component.
[Example: The syntactic equivalence of connection deselection ensures that connect-statements in for-loops can be deselected:
In this case the deselection removes all of the connect-statements.]