开发者

How do I return different type from overridden method?

开发者 https://www.devze.com 2022-12-16 12:56 出处:网络
I\'m extending the AS3 class Rectangle with a class called Bin. I want to override the Rectangle clone() method with a method that returns a Bin object, not a Rectangle object. If I try to override th

I'm extending the AS3 class Rectangle with a class called Bin. I want to override the Rectangle clone() method with a method that returns a Bin object, not a Rectangle object. If I try to override th开发者_如何学运维e clone method but specify Bin as the return type, I get a #1023: Incompatible override error. Here's my Bin class:

package {

    import flash.geom.Rectangle;

    public class Bin extends Rectangle {

        public function Bin(x:Number = 0, y:Number = 0, width:Number = 0, height:Number = 0) {
            super(x, y, width, height);
        }

        override public function clone():Rectangle {
            return new Bin(x, y, width, height);
        }

    }

}

This class works, but when I use the clone() method to create a new Bin instance, I get type errors when I try to use the Bin methods on the new instance.

How do I override clone() and send an actual Bin instance?


Technically, you can't change the signature when you override a method. In your case, though, its not a huge problem. You just have to cast the resulting object to type Bin after calling the clone method.

0

精彩评论

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