开发者

Call override child class function?

开发者 https://www.devze.com 2023-01-25 06:10 出处:网络
I have two child classes ClassA and ClassB both inherit the same base class. I also have a function that has a parameter which could be an instance开发者_开发问答 of either child classes.

I have two child classes ClassA and ClassB both inherit the same base class.

I also have a function that has a parameter which could be an instance开发者_开发问答 of either child classes.

function Test(instance):void //instance is either a ClassA or ClassB instance
{
    instance.DoSomething();
}

However, when I run the test, it's always the BaseClass.DoSomething() get called. How can I use the same function (DoSomething()), but call child class function instead of the base class one?

Thanks


You should type your instance as a BaseClass if you intend to call either ClassA or ClassB

 //instance is either a ClassA or ClassB instance
 function Test(instance:BaseClass):void
 {
     instance.DoSomething();
 }

Since you implement the DoSomething() method in the BaseClass, you can override the function in ClassA & ClassB in order to have specific behaviors for each class.

  //in ClassA
  override public function DoSomething():void
  {
      trace('I\'m being called in ClassA');
   } 

  //in ClassB
  override public function DoSomething():void
  {
      trace('I\'m being called in ClassB');
   } 

You can now try this:

    var classA:BaseClass = new ClassA();
    var classB:BaseClass = new ClassB();

    Test(classA);
    Test(classB);


try

(instance as ClassA).DoSomething();
0

精彩评论

暂无评论...
验证码 换一张
取 消