ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
重写字段是创建类的层级的结构。许多设计模式使用到它,但是这里我们只探索基本的功能。为了在类中使用重写,需要这个类有一个父类(第2.3.2)。思考下面的例子: > Overriding fields is instrumental for creating class hierarchies. Many design patterns utilize it, but here we will explore only the basic functionality. In order to use overrides in a class, it is required that this class has a parent class (2.3.2). Let us consider the following example: ~~~ class Base { public function new() { } public function myMethod() { return "Base"; } } class Child extends Base { public override function myMethod() { return "Child"; } } class Main { static public function main() { var child:Base = new Child(); trace(child.myMethod()); // Child } } ~~~ 这里重要的组件是: > The important components here are: * Base 类,有一个方法 myMethod和一个构造函数 * Child类,继承Base类也有一个方法 myMethod,通过 override关键字声明 * Main 类,它的main方法创建一个Child类的实例,分配它到一个变量 child ,显式的声明类型为Base,然后在其上调用 myMethod() > * the class Base which has a method myMethod and a constructor, > * the class Child which extends Base and also has a method myMethod being declared with override, and > * the Main class whose main method creates an instance of Child, assigns it to a variable child of explicit type Base and calls myMethod() on it. 变量 child 被显式的类型化为 Base 来突出一个重要的不同:在编译器时类型被认为是 Base,但是运行时仍然查找正确的方法即类Child中的 myMethod。这是因为字段访问在运行时是动态解析的。 > The variable child is explicitly typed as Base to highlight an important difference: At compile-time the type is known to be Base,but the runtime still finds the correct method myMethod on class Child. This is because field access is resolved dynamically at runtime. Child 类可以访问它重载的方法,通过调用 super.methodName(): > The Child class can access methods it has overriden by calling super.methodName(): ~~~ class Base { public function new() { } public function myMethod() { return "Base"; } } class Child extends Base { public override function myMethod() { return "Child"; } public function callHome() { return super.myMethod(); } } class Main { static public function main() { var child = new Child(); trace(child.callHome()); // Base } } ~~~ 继承(第2.3.2节)中解释了super()在一个新的构造函数中的使用。 > The section on Inheritance (Section 2.3.2) explains the use of super() from within a new constructor.