在子类AS3中使用super()

时间:2013-01-11 19:19:26

标签: actionscript-3

为了解释我的问题,我写了一些代码。

这是超类:

package

{
    public class Cclass
    {
        public function Cclass(a:int, words:String)
        {
            trace("i am:"+a," years old and i will:"+words," you");
        }
    }
}

这是子类:

package
{
    public class Dclass extends Cclass
    {
        public function Dclass(a:int, words:String)
        {
            super(a, words);
            trace(a, words);

        }
    }
}

当我测试它时,我得到以下输出:

i am:5  years old and i will:kill  you
i am:6  years old and i will:strangle  you
6 strangle

super运行Cclass的构造函数并再次执行相同的操作,但是如果我尝试在没有“super(a,words)”的情况下运行它,则它不起作用,这是可以理解的。我的问题是如何使Dclass仅显示trace(a, words);而不运行Cclass的构造函数。我想得到这个输出:

i am:5  years old and i will:kill  you
6 strangle

2 个答案:

答案 0 :(得分:1)

扩展类时,AS3运行时将自动调用基类构造函数 因此,您可以假设在扩展类时,无论您是否编写代码,都会发生super.constructor 这就是为什么最好不要在构造函数中包含任何代码。

这并不意味着通过一点点按摩你就无法解决它

public class Cclass{
  public function Cclass( ){
  }
  public function doTrace( a:int, words:String):void{
    trace("i am:"+a," years old and i will:"+words," you");
  }
}

public class Dclass extends Cclass{
    public function Dclass(){
      //super();// this is implied that it will always happen
    }
    public function myTrace(a:int, words:String):void{
        this.doTrace(a, words);
    }
}

var dClass:Dclass = new Dclass()
dClass.myTrace(5,'kill')

答案 1 :(得分:1)

超级构造函数总是在actionscript中运行,如果你没有声明它,它会自动运行它。最好的方法是使它成为一种功能。

public class cc {

     public function doSomething(a:int, words:String)
     {
         trace("i am:"+a," years old and i will:"+words," you");
     }
}

public class dd extends cc {

     override public function doSomething(a:int, words:String) {
         trace("i am:"+a," years old and i will:"+words," you");
     }
}

var d = new dd();
d.doSomething(5, 'kill');