26

I have

    public function Shard() {
    }

    public function Shard(x:Number, y:Number, vx:Number, vy:Number, rotation:Number, spin:Number)
    {
      ...
    }

And I got on the second constructor:

Multiple constructor definitions found. Constructor may not be defined in code.

So, ActionScript-3 cannot have multiple constructors?

1
  • 1
    Why do you want multiple constructors? Are some of the parameters optional? Commented Aug 24, 2010 at 19:18

2 Answers 2

33

No you can't have multiple contructor neither the same function with different signature, but you can use default arguments :

public function Shard(x:Number=NaN, y:Number=NaN) {
  //...
}

then you can call new Shard() or new Shard(100) or new Shard(100, 200)

or you can also use variable arguments:

public function Shard(...args){
 if (args.length==0) {
   //...
 } else {
  //...
  var firstArg:Object=args[0];
  //...
 }
}
Sign up to request clarification or add additional context in comments.

Comments

12

It's even broader than that. AS3 has no support at all for function overloading.

You can simulate the appearance of multiple constructors with parameter defaults and/or dynamically dispatching the parameters to various init methods. Alternatively, custom object factories or static creation methods could help.

1 Comment

+1. I've used static methods for initializing and returning a new instances (kind of like factories). Generally, these methods are defined in the same class and are only meant to simplify the interface for the calling code. It's a simple and effective workaround in some cases (though if you want to have different of these "constructors" you have to do the name mangling since the compiler doesn't do it for you)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.