----- Original Message ----- 
From: "David_Stafford" <[EMAIL PROTECTED]>
To: <flexcoders@yahoogroups.com>
Sent: Wednesday, February 07, 2007 2:12 AM
Subject: [flexcoders] Returning 'this' from an overridden method?


> Please pardon this simple-minded question from an AS3 novice.
>
> My base class often returns 'this' from methods which makes it
> convenient to write code like:
>
>   camera.move( 10, 12 ).rotateX( 45 ).rotateY( 90 );
>
> The problem comes when code extends the base class and overrides one
> of these functions.  The compiler insists, correctly, that the return
> type of an overriding function must match the one in the base class.
> What I want to do is return the 'this' object that is of the type of
> the derived class.  Is this possible?
>
> The following is a contrived example to demonstrate.  It won't
> compile because the overridden function in the derived class wants to
> return a type of MyCamera rather than Camera:

This is the correct behaviour. The derived class is MyCamera and any
reference to this, either in the derived class or it's parent will be
working with an object of class MyCamera not Camera.

Make the return type Camera, then it will work. You will be returning an
object reference of class Camera, but in fact it is an object reference to
an object of class MyCamera. You can then cast it elsewhere as a 'MyCamera'
in the application.

The problem is that you are trying to change the signature of the method
that you are overriding.

Paul

> public class Camera
>   {
>   var x:int = 0;
>   var y:int = 0;
>
>   public function move( x:int, y:int ) :Camera
>     {
>     this.x += x;
>     this.y += y;
>
>     return( this );
>     }
>   }
>
> public class MyCamera extends Camera
>   {
>   override public function move( x:int, y:int ) :MyCamera
>     {
>     super.move( x, y );
>
>     if( x < 0 )  x = 0;
>     if( y < 0 )  y = 0;
>
>     return( this );
>     }
>   }
>
>
>
>
>
> --
> Flexcoders Mailing List
> FAQ: http://groups.yahoo.com/group/flexcoders/files/flexcodersFAQ.txt
> Search Archives: http://www.mail-archive.com/flexcoders%40yahoogroups.com
> Yahoo! Groups Links
>
>
>
>


Reply via email to