从AS3中的基类调用子类的重写函数

时间:2014-12-22 15:14:07

标签: actionscript-3 oop

我有一个名为 Screen 的课程:

public class Screen extends GameObject
{
    //GameObject is a class extending Sprite and implemented by just some variables and methods 

    public static var scrStage:Stage;

    public function Screen(argStage:Stage) {
        scrStage = argStage;
        initObjects();
    }

    private function initObjects():void {
        // empty method
    }

}

一个名为 PlayScreen 的课程:

public class PlayScreen extends Screen
{
    //declares TextFields and GameObjects

    public function PlayScreen(argStage:Stage) {
        super(argStage);
        //addChild those TextFields and GameObjects
    }

    private function initObjects():void {
        // initializes those TextFields and GameObjects
    }

}

}

当调用 PlayScreen 的构造函数时,也会调用 Screen 的构造函数。在其中, scrStage 被分配给 argStage initObjects ()被调用。应该调用 PlayScreen (子类)的 initObjects (),但是 Screen (基类)&#39; s <而是调用em> initObjects ()。

所以当你调用PlayScreen的构造函数时,你会介意帮我调用PlayScreen的initObjects()吗?提前谢谢。


更新

糟糕。 在我的项目中的其他地方调试之后,我找到了解决方案:

//edit in Screen class
private function initObjects():void {}
//to
protected function initObjects():void {}
//or public

//and in PlayScreen class
private function initObjects():void {}
//to
protected override function initObjects():void {}
//or public 

1 个答案:

答案 0 :(得分:1)

您是否可以不在屏幕下拨打initObjects,因为无论如何它都是空方法,并从PlayScreen中调用它:

public class Screen extends GameObject
{
    //GameObject is a class extending Sprite and implemented by just some variables and methods 

    public static var scrStage:Stage;

    public function Screen(argStage:Stage) {
        scrStage = argStage;
    }
}

public class PlayScreen extends Screen
{
    //declares TextFields and GameObjects

    public function PlayScreen(argStage:Stage) {
        super(argStage);
        //addChild those TextFields and GameObjects
        initObjects();
    }

    private function initObjects():void {
        // initializes those TextFields and GameObjects
    }

}