Question

I am trying to write a method that creates random plants and returns the object of created plant as Plant. In example below the method createPlant() is of type Plant and returns an object of child class Tree. As it turns out my way of thinking is erroneous. The error provided by Eclipse is: "This method must return a result of type Plant". So how should I go about creating such method?

public abstract class Plant {
    ...
}

public class Tree extends Plant {
    ...
}

public class Bush extends Plant {
    ...
}

public class Map {
    private Plant plant;
    ...
    public static Plant createPlant(float x, float y) { // This method must return a result of type Plant
        Random generator = new Random();            
        switch (generator.nextInt(2)) {
            case 0:
                return new Tree(x, y);
            case 1:
                return new Bush(x, y);
        }
    }
}
Was it helpful?

Solution

Add default case of null.

    switch (generator.nextInt(2)) {
        case 0:
            return new Tree(x, y);
        case 1:
            return new Bush(x, y);
        default:                         // Requires default case
            return null;
    }

Or create a dummy NoPlant class

  public class NoPlant extends Plant {
     ...
  }

Now use in this way

    switch (generator.nextInt(2)) {
        case 0:
            return new Tree(x, y);
        case 1:
            return new Bush(x, y);
        default:                         // Requires default case
            return new NoPlant();
    }

--EDIT--

Try in this way also

    int random=generator.nextInt(2); // return either 0 or 1

    if(random==0){
        return new Tree(x,y);
    }else{
        return new Bush(x, y);
    }

OTHER TIPS

No, from an object oriented perspective this is absolutely okay. A plant is a general entity, whereas the tree is specialized in some way.

The main point is that the tree is also a plant (is-a-relation) so a method returning a plant can return anything that is at least as general as a plant but also may be more specialized.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top