在AS3中,如果我有一个类:
public class dude
{
//default value for a dude
protected var _strength:Number = 1;
public function dude( ):void
{ super( );
//todo... calculate abilities of a dude based on his strength.
}
}
和子类
public class superDude extends dude
{
public function superDude( ):void
{
_strength = 100;
super( );
trace( "strength of superDude: " + _strength );
}
}
这将追溯 superDude的强度为1 。我期望我在子类中设置的变量(在调用超类构造函数之前)保留。
有没有办法在子类构造函数中分配类变量,而这些变量不会被超类构造器覆盖?或者我应该将它们作为构造函数变量传递?
答案 0 :(得分:3)
将_strength设置为100后,您正在调用super();这条指令将从超类调用构造函数,该构造函数将_strength更改为1(变量初始化在构造函数中发生)。没有办法防止这种情况,我认为你应该在初始化变量之前调用super()。
答案 1 :(得分:1)
首先,从子类构造函数中隐式调用默认的超类构造函数(不带任何参数)。所以你不需要明确地调用它。
如果超类构造函数接受了参数,则需要显式调用它,并且该调用必须是子类构造函数中的第一个语句。
答案 2 :(得分:0)
在回答Kayes的回答时,我必须提到“超级”不应该总是先被调用。
理想情况下,构造函数参数应该被复制到当前类ASAP的实例变量中(即在调用super之前),因为它们可能需要可用于可被超级调用的重写方法类构造函数。如果在调用super之前未初始化这些变量,则它们将不可用于重写方法。另一方面,在您需要访问任何阶段实例之前,应该调用super。
因此在调用super之前初始化 current 类的变量是正确的,但是在调用super之前初始化子类中 super 类的公共/受保护变量是不正确的。 ,因为在调用super时它们会被重置。
public class GUIControlSubclass extends GUIControl
{
private var _param:String;
public function GUIControlSubclass( param:String )
{
_param = param; //variable of this class must be assigned before calling super, so it's available to override of initLayout
_backgroundColor = 0xffffff; //it is incorrect to assign protected/public variable of super class here, since it will be reset by super call
super(); //super class constructor will call initLayout, which will call this subclass's override of it; super class constructor itself should call it's own "super" method *before* calling initLayout, to ensure stage instances are constructed and available to initLayout
}
override protected function initLayout():void
{
super.initLayout();
//IF _param WAS NOT SET **BEFORE** CALLING SUPER IN THE CONSTRUCTOR, ITS VALUE WOULD BE NULL HERE, SINCE SUPER TRIGGERS THIS METHOD, THEREFORE _param MUST BE ASSIGNED BEFORE SUPER IS CALLED
}
}