views:

52

answers:

4

Say I have four sub-classes of 'Car'. One for each color. I want to have one function that can build and return a 'color-car' sub-class based on the passed value. This is a dumb example, I know, but it is precisely what I am trying to do only on a smaller scale.

public class Car
{
}

public class BlueCar extends Car
{
}

You get it.

Then, in another (helper) class, I have a function which takes in a string of the color and returns the correct sub-class.

public function GetCarFromColor(_color:String):Car
{
    if (_color == "blue")
    {
        var myCar:BlueCar = new BlueCar;
        return myCar;
    } else if (_color == "red")
    {
        var myCar:RedCar = new RedCar;
        return myCar;
    }

Ok. You get it. This doesn't work for a reason unknown to me. I get 1118 errors which complain about conversion of BlueCar into Car, etc...

Can someone help me out here? Thanks!

+1  A: 

You should try casting your derived class to the base class before returning it back.

Not sure about actionscript but in C++ you could do it like this

Base *GetCarFromColor() { Base *b1; b1 = new D1; return b1; }

GJ
Don't know actionscript but implicit upcasting not being implemented seems like a bit of an oversight by the compiler developers.
Pierreten
Ok. And how would I do that? :)
NJ
Modified my answer to show you how can you do it in C++, may be you dont have pointers in actionscript.
GJ
Thanks! It's working.
NJ
A: 

Maybe you should use an interface instead?

public interface ICar
{
}

public class BlueCar implements ICar
{
}

public function GetCarFromColor(_color:String):ICar
{
}
James Ward
I tried that, but it didn't seem to work. Would I still need to cast as suggested above?
NJ
I don't think you would need a cast if you use interfaces. But you shouldn't need a cast with subclasses either.
James Ward
+2  A: 

Make the return variable to be of the supertype:

public function GetCarFromColor(_color:String):Car
{
    var myCar:Car
    if (_color == "blue")
    {
        myCar = new BlueCar;
        return myCar;
    } else if (_color == "red")
    {
        myCar = new RedCar;
        return myCar;
    }

This should now compile ok.

Matt Allen
A: 

The reason you were getting errors is because you have two local variables of the same name with different types in one function:

var myCar:BlueCar = new BlueCar;
var myCar:RedCar = new RedCar;

The variable myCar is typed as both BlueCar and RedCar. In ActionScript 3, variables are always scoped to the entire function. In other languages, like Java, I know that if statements and loops create a new block-level scope, but that's not the case here.

As Matt Allen suggested, typing myCar as the superclass, Car, should stop these compiler errors.

joshtynjala