xxiaojun
xxiaojun

Reputation: 81

Call override child class function?

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

Upvotes: 0

Views: 403

Answers (2)

PatrickS
PatrickS

Reputation: 9572

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);

Upvotes: 3

www0z0k
www0z0k

Reputation: 4434

try

(instance as ClassA).DoSomething();

Upvotes: 0

Related Questions