Inheritance Modelica:如何将Child类型的实例分配到Parent类型的变量中?
我有以下课程:Inheritance Modelica:如何将Child类型的实例分配到Parent类型的变量中?,inheritance,modelica,Inheritance,Modelica,我有以下课程: class Parent end parent; class Child extends Parent; end Child; 在另一个类中,我需要声明一个Parent类型的变量 并通过Child类型的实例对其进行初始化; 类似于Java语句的内容: Parent p = new Child(); 我怎样才能在Modelica中做到这一点 感谢Modelica的类概念无法与Java的类概念相比。例如,您不创建新对象,因此 Parent p = new Child(
class Parent
end parent;
class Child
extends Parent;
end Child;
在另一个类中,我需要声明一个Parent类型的变量
并通过Child类型的实例对其进行初始化;
类似于Java语句的内容:
Parent p = new Child();
我怎样才能在Modelica中做到这一点
感谢Modelica的类概念无法与Java的类概念相比。例如,您不创建新对象,因此
Parent p = new Child();
相反,您只需通过编写
Parent p;
因此,不能将子对象指定给父基类。相反,Modelica的继承特性可以用于重新声明。这意味着,您可以在某处实例化一个可替换的基类,稍后可以使用redeclare
语句对其进行更改
请参见下面的一个简单示例Example2
将cls
重新声明到子类,因此我们在模拟它时得到cls.c=2
package Demo
class Parent
constant Real c=1;
end Parent;
class Child
extends Parent(c=2);
end Child;
model Example1
replaceable Parent cls;
end Example1;
model Example2
extends Example1(redeclare Child cls);
end Example2;
end Demo;
总而言之,可以说Modelica的面向对象性降低到
- 继承,使用
扩展
- 重新声明,使用
重新声明
package Inheritance
import SI = Modelica.SIunits;
connector PositivePin "Positive pin of an electrical component"
SI.ElectricPotential v "Potential at the pin";
flow SI.Current i "Current flowing into the pin";
end PositivePin;
partial model OnePort
"Component with two electrical pins p and n and current i from p to n"
SI.Voltage v "Voltage drop of the two pins (= p.v - n.v)";
SI.Current i "Current flowing from pin p to pin n";
Inheritance.PositivePin p "Positive electrical pin";
Modelica.Electrical.Analog.Interfaces.NegativePin n "Negative electrical pin";
equation
v = p.v - n.v;
0 = p.i + n.i;
i = p.i;
end OnePort;
model Resistor "Ideal linear electrical resistor"
parameter SI.Resistance R = 1
"Resistance at temperature T_ref";
extends Inheritance.OnePort;
equation
v = R*i;
end Resistor;
model Circuit
Resistor r( R=10);
Modelica.Electrical.Analog.Basic.Ground ground;
Modelica.Electrical.Analog.Sources.ConstantVoltage constantVoltage(V=1);
equation
connect(constantVoltage.n, ground.p);
connect(constantVoltage.p, r.n);
connect(r.p, ground.p);
end Circuit;
end Inheritance;
因此连接器类的实例p
Inheritance.PositivePin p;
将部分模型中的变量i、v引入OnePort(请参阅以了解潜在变量和流量变量)
在模型类电阻器中
extends Inheritance.OnePort;
实例化变量
- i、 五
- p、 i,p.v通过类PositivePin的实例p
- n、 i,n.v通过类NegativePin的实例n
- v=p.v-n.v李>
- 0=p.i+n.i李>
- i=p.i李>
Resistor r(R=10);
使用所谓的修饰符实例化电阻器类,以便实例r具有电阻值r=10,而不是默认的类值r=1