# Chapter 7 Inheritance, Modification, and Redeclaration

(July 13, 2021)

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.

## 7.1 Inheritance – Extends Clause

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:

extends-clause :
extends name [ class-modification ] [annotation]

The name of the base class is looked up in the partially flattened enclosing class (section 5.2) of the extends-clause. The 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

• the optional class-modification of the extends-clause

in that order.

[Example:

class A
parameter Real a, b;
end A;
class B
extends A(b = 2);
end B;
class C
extends B(a = 1);
end C;

]

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:

class Cinstance
parameter Real a = 1;
parameter Real b = 2;
end Cinstance;

The ordering of the merging rules ensures that, given classes A and B defined above,

class C2
B bcomp(b = 3);
end C2;

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.

[Clarifiying order:

function A
input Real a;
input Real b;
end A;
function B
extends A;
input Real a;
end B;
// The inputs of B are "a, b" in that order; and the "input Real a;" is ignored.

]

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.]

### 7.1.1 Multiple Inheritance

Multiple inheritance is possible since multiple extends-clauses can be present in a class.

### 7.1.2 Inheritance of Protected and Public Elements

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).

### 7.1.3 Restrictions on the Kind of Base Class

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):

 Derived Class package operator function operator function type record operator record Base Class package operator function operator type record operator expandable connector block model class function record connector yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes

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.]

[Example:

record RecordA
$\ldots$
end RecordA;
package PackageA
$\ldots$
end PackageA;
package PackageB
extends PackageA; // fine
end PackageB;
model ModelA
extends RecordA; // fine
end ModelA;
model ModelB
extends PackageA; // error, inheritance not allowed
end ModelB;

]

### 7.1.4 Restrictions on Base Classes and Constraining Types to be Transitively Non-Replaceable

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 $\ldots$ 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.]

## 7.2 Modifications

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:

• variable declarations

• short class declarations

• extends-clauses

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:

Real altitude(start = 59404);

]

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:

model B
parameter Real x;
package Medium = Modelica.Media.PartialMedium;
end B;
model C
parameter Real x = 2;
package Medium = Modelica.Media.PartialMedium;
B b(x = x, redeclare package Medium = Medium);
// The ’x’ and ’Medium’ being modified are declared in the model B.
// The modifiers ’= x’ and ’= Medium’ are found in the model C.
end C;
model D
parameter Real x = 3;
package Medium = Modelica.Media.PartialMedium;
C c(b(x = x, redeclare package Medium = Medium));
// The ’x’ and ’Medium’ being modified are declared in the model B.
// The modifiers ’= x’ and ’= Medium’ are found in the model D.
end D;

]

When present, the description-string of a modifier overrides the existing description.

### 7.2.1 Syntax of Modifications and Redeclarations

The syntax is defined in the grammar, section A.2.5.

### 7.2.2 Modification Environment

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.]

### 7.2.3 Merging of Modifications

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:

class C1
class C11
parameter Real x;
end C11;
end C1;
class C2
class C21
$\ldots$
end C21;
end C2;
class C3
extends C1;
C11 t(x = 3); // ok, C11 has been inherited from C1
C21 u; // ok, even though C21 is inherited below
extends C2;
end C3;

The following example demonstrates overriding part of non-simple component:

record A
parameter Real x;
parameter Real y;
end A;
model B
parameter A a = A(2, 3);
end B;
model C
B b1(a(x = 4)); // Error since attempting to override value for a.x when a has a value.
end C;

The modification environment of the declaration of t is (x = 3). The modification environment is built by merging class modifications, as shown by:

class C1
parameter Real a;
end C1;
class C2
parameter Real b;
parameter Real c;
end C2;
class C3
parameter Real x1; // No default value
parameter Real x2 = 2; // Default value 2
parameter C1 x3; // No default value for x3.a
parameter C2 x4(b = 4); // x4.b has default value 4
parameter C1 x5(a = 5); // x5.a has default value 5
extends C1; // No default value for inherited element a
extends C2(b = 6, c = 77); // Inherited b has default value 6
end C3;
class C4
extends C3(x2 = 22, x3(a = 33), x4(c = 44), x5 = x3, a = 55, b = 66);
end C4;

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:

Variable Default value
x1 none
x2 22
x3.a 33
x4.b 4
x4.c 44
x5.a x3.a
a 55
b 66
c 77

]

### 7.2.4 Single Modification

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.

[Example:

class C1
Real x[3];
end C1;
class C2 = C1(x = ones(3), x = ones(3)); // Error: x designated twice
class C3
class C4
Real x;
end C4;
C4 a(final x.unit = "V", x.displayUnit = "mV", x = 5.0);
// Ok, different attributes designated (unit, displayUnit and value)
// identical to:
C4 b(x(final unit = "V", displayUnit = "mV") = 5.0));
end C3;

The following examples are incorrect:

m1(r = 1.5, r = 1.6) // Multiple modifier for r (its value)
m1(r = 1.5, r = 1.5) // Multiple modifier for r (its value) - even if identical
m1(r.start = 2, r(start = 3)) // Multiple modifier for r.start
m1(x.r = 1.5 "x", x.r(start = 2.0) "y")) // Multiple description-string for x.r
m1(r = R(), r(y = 2)) // Multiple modifier for r.y - both direct value and
// part of record

The following examples are correct:

m1(r = 1.5, r(start = 2.0))
m1(r = 1.6, r "x")
m1(r = R(), r(y(min = 2)))

]

### 7.2.5 Modifiers for Array Elements

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.

[Example:

model C
parameter Real a[3];
parameter Real d;
end C;
model B
C c[5](each a = {1, 2, 3}, d = {1, 2, 3, 4, 5});
parameter Real b = 0;
end B;

This implies c[i].a[j] = j and c[i].d = i.

model D
B b(each c.a = {3, 4, 5}, c.d = {2, 3, 4, 5, 6});
// Equivalent to:
B b2(c(each a = {3, 4, 5}, d = {2, 3, 4, 5, 6}));
end D;

This implies b.c[i].a[j] = 2+j and b.c[i].d = 1+i.

model E
B b[2](each c(each a = {1, 2, 3}, d = {1, 2, 3, 4, 5}), p = {1, 2});
// Without the first each one would have to use:
B b2[2](c(each a = {1, 2, 3}, d = fill({1, 2, 3, 4, 5}, 2)), p = {1, 2});
end E;

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.

model F
Real fail1[2](each start = {1, 2}); // Illegal
Real work1[2](each start = 1);      // Legal
Real[2] fail2(each start = {1, 2}); // Illegal
Real[2] work2(each start = 2);      // Legal
end F;

]

### 7.2.6 Final Element Modification Prevention

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.

type Angle =
Real(final quantity = "Angle", final unit = "rad", displayUnit = "deg");
model TransferFunction
parameter Real b[:] = {1} "numerator coefficient vector";
parameter Real a[:] = {1, 1} "denominator coefficient vector";
$\ldots$
end TransferFunction;
model PI "PI controller"
parameter Real k = 1 "gain";
parameter Real T = 1 "time constant";
TransferFunction tf(final b = k * {T, 1}, final a = {T, 0});
end PI;
model Test
PI c1(k = 2, T = 3); // fine, will indirectly change tf.b to 2 * {3, 1}
PI c2(tf(b = {1}));  // error, b is declared as final
end Test;

]

[Example: Final class declaration.

model Test2
final model MyTF = TransferFunction(b = {1, 2});
/* Equivalently:
final model MyTF = TransferFunction(final a, final b = {1, 2});
*/
MyTF tf1;                        // fine
MyTF tf2(a = {1, 2});            // error, all elements in MyTF are final
model M = MyTF(a = {4});         // error, all elements in MyTF are final
model TFX
extends MyTF;                  // fine
Real foo = 1.0;
end TFX;
TFX tfx(foo = 2.0);              // fine, foo is not from MyRF
TFX tfx2(a = {1, 3});            // error, all elements from MyTF are final
model TFX3 = TFX(a = {1, 4});    // error, all elements from MyTF are final
end Test2;

]

## 7.3 Redeclaration

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:

• public, protected

• inner, outer

• constraining type according to rules in section 7.3.2.

The groups that are only valid for components:

• flow, stream

• discrete, parameter, constant

• input, output

• array dimensions

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.]

[

model HeatExchanger
replaceable parameter GeometryRecord geometry;
replaceable input Real u[2];
end HeatExchanger;
HeatExchanger(
/*redeclare*/ replaceable /*parameter*/ GeoHorizontal geometry,
redeclare /*input*/ Modelica.Units.SI.Angle u /*[2]*/);
// The semantics ensure that parts in /*.*/ are automatically added
// from the declarations in HeatExchanger.

Example of arrays on the left of the component name:

model M
replaceable Real [4] x[2];
// Seen as syntactic sugar for "replaceable Real x[2, 4];"
// Note the order.
end M;
M m(redeclare Modelica.Units.SI.Length x[2, 4]); // Valid redeclare of the type

]

### 7.3.1 The class extends Redeclaration Mechanism

A class declaration of the type redeclare class extends B($\ldots$), 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($\ldots$) 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($\ldots$) 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):

class-definition :
[ encapsulated ] class-prefixes
class-specifier
class-specifier : long-class-specifier | $\ldots$
long-class-specifier : $\ldots$
| extends IDENT [ class-modification ] description-string
composition end IDENT

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:

element :
import-clause |
extends-clause |
[ redeclare ]
[ final ]
[ inner ] [ outer ]
( ( class-definition | component-clause) |
replaceable ( class-definition | component-clause)
[constraining-clause comment])

[Example to extend from existing packages:

package PowerTrain // library from someone else
replaceable package GearBoxes
$\ldots$
end GearBoxes;
end PowerTrain;
package MyPowerTrain
extends PowerTrain; // use all classes from PowerTrain
redeclare package extends GearBoxes // add classes to sublibrary
$\ldots$
end GearBoxes;
end MyPowerTrain;

Example for an advanced type of package structuring with constraining types:

partial package PartialMedium "Generic medium interface"
constant Integer nX "number of substances";
replaceable partial model BaseProperties
Real X[nX];
$\ldots$
end BaseProperties;
replaceable partial function dynamicViscosity
input Real p;
output Real eta;
$\ldots$
end dynamicViscosity;
end PartialMedium;
package MoistAir "Special type of medium"
extends PartialMedium(nX=2);
redeclare model extends BaseProperties(T(stateSelect = StateSelect.prefer))
// replaces BaseProperties by a new implementation and
// extends from Baseproperties with modification
// note, nX = 2 (!)
equation
X = {0, 1};
$\ldots$
end BaseProperties;
redeclare function extends dynamicViscosity
// replaces dynamicViscosity by a new implementation and
// extends from dynamicViscosity
algorithm
eta := 2 * p;
end dynamicViscosity;
end MoistAir;

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:

package MoistAir2 "Alternative definition that does not work"
extends PartialMedium(nX=2,
redeclare model BaseProperties = MoistAir_BaseProperties,
redeclare function dynamicViscosity = MoistAir_dynamicViscosity);
model MoistAir_BaseProperties
// wrong model since nX has no value
extends PartialMedium.BaseProperties;
equation
X = {1, 0};
end MoistAir_BaseProperties;
function MoistAir_dynamicViscosity
extends PartialMedium.dynamicViscosity;
algorithm
eta := p;
end MoistAir_dynamicViscosity;
end MoistAir2;

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.]

### 7.3.2 Constraining Type

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:

constraining-clause :
constrainedby name [ class-modification ]

[Example: Merging of modifiers:

class A
parameter Real x;
end A;
class B
parameter Real x = 3.14, y; // B is a subtype of A
end B;
class C
replaceable A a(x = 1);
end C;
class D
extends C(redeclare B a(y = 2));
end D;

which is equivalent to defining D as

class D
B a(x = 1, y = 2);
end D;

A modification of the constraining type is automatically applied in subsequent redeclarations:

model ElectricalSource
replaceable SineSource source constrainedby MO(final n=5);
$\ldots$
end ElectricalSource;
model TrapezoidalSource
extends ElectricalSource(
redeclare Trapezoidal source); // source.n=5
end TrapezoidalSource;

A modification of the base type without a constraining type is automatically applied in subsequent redeclarations:

model Circuit
replaceable model NonlinearResistor = Resistor(R=100);
$\ldots$
end Circuit;
model Circuit2
extends Circuit(
redeclare replaceable model NonlinearResistor
= ThermoResistor(T0 = 300));
// As a result of the modification on the base type,
// the default value of R is 100
end Circuit2;
model Circuit3
extends Circuit2(
redeclare replaceable model NonlinearResistor
= Resistor(R = 200));
// The T0 modification is not applied because it did not
// appear in the original declaration
end Circuit3;

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:

model Circuit4
extends Circuit2(
redeclare replaceable model NonlinearResistor
= ThermoResistor constrainedby ThermoResistor);
end Circuit4;
model Circuit5
extends Circuit4(
redeclare replaceable model NonlinearResistor = Resistor); // illegal
end Circuit5;

]

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.

[Example:

replaceable T1 x[n] constrainedby T2;
replaceable type T=T1[n] constrainedby T2;
replaceable T1[n] x constrainedby T2;

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[3]) then T1 must also be vector type.]

#### 7.3.2.1 Constraining-clause annotations

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.]

[Example:

Resistor constrainedby TwoPin "The Load"; // Recommended
constrainedby TwoPin "The Load"; // Recommended

]

### 7.3.3 Restrictions on Redeclarations

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.]

### 7.3.4 Annotation Choices for Suggested Redeclarations and Modifications

A declaration can have an annotation choices containing modifiers on choice, where each of them indicates a suitable redeclaration or modifications of the element.

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 a replaceable element indicates that tools should automatically construct a menu with choices of elements 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.$\ldots$.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. This menu can be disabled using annotation choicesAllMatching = false.

[The behavior when choicesAllMatching is not specified; ideally it should present (at least) the same choices as for choicesAllMatching = true; but if it takes (too long) time to present the list it is better to have choicesAllMatching = false.]

[Example:

replaceable model MyResistor = Resistor
annotation(choices(
choice(redeclare model MyResistor=lib2.Resistor(a={2}) "$\ldots$"),
choice(redeclare model MyResistor=lib2.Resistor2 "$\ldots$")));
replaceable Resistor Load(R = 2) constrainedby TwoPin
annotation(choices(
choice(redeclare lib2.Resistor Load(a={2}) "$\ldots$"),
choice(redeclare Capacitor Load(L=3) "$\ldots$")));
replaceable FrictionFunction a(func = exp) constrainedby Friction
annotation(choices(
choice(redeclare ConstantFriction a(c=1) "$\ldots$"),
choice(redeclare TableFriction a(table="$\ldots$") "$\ldots$"),
choice(redeclare FunctionFriction a(func=exp) "$\ldots$")));
replaceable package Medium = Modelica.Media.Water.ConstantPropertyLiquidWater
constrainedby Modelica.Media.Interfaces.PartialMedium
annotation(choicesAllMatching = true);

It can also be applied to nonreplaceable declarations, e.g. to describe enumerations.

type KindOfController = Integer(min = 1, max = 3)
annotation(choices(
choice = 1 "P",
choice = 2 "PI",
choice = 3 "PID"));
model A
parameter KindOfController x;
end A;
A a(x = 3 "PID");

It can also be applied to Boolean variables to define a check box.

parameter Boolean useHeatPort = false annotation(choices(checkBox = true));

]