views:

142

answers:

2

For a custom derived class "Vector2" from flash.geom.Point, when trying to override the clone() method (similar to add(), subtract() methods that will return the type itself), it will always complain about incompatible overriding 'cuz the return type has been altered from "Point" to "Vector2".

import flash.geom.Point;

public class Vector2 extends Point
{
    //Constructor is good
    public function Vector2(x:Number = 0, y:Number = 0)
    {
        super(x,y);
    }

    // Error: Incompatible overriding
    override public function clone():Vector2  //return type has to be "Point"
    {
        return new Vector2(this.x , this.y);
    }
}

How can we correctly reuse/override the methods provided by the super classes as supposed to create our own one (e.g. : a new clone1() method), or simply we just can't?

Thanks.

+1  A: 

you can't, because to override you have to keep the same function signature. Good news is that since your 'Vector2' class is a Point, you can have a function that creates a Vector2 object and returns it as a Point. (And you can cast it back when you need it)

kajyr
+2  A: 

The feature you are talking about is called covariant return type (http://en.wikipedia.org/wiki/Covariant_return_type). C++ and Java, for example, have this feature, alas ActionScript does not.

putgeminmouth