This site requires JavaScript, please enable it in your browser!
Greenfoot back
rockon411
rockon411 wrote ...

2017/3/24

Assigning a Value and Returning it

rockon411 rockon411

2017/3/24

#
I have created a parent class with a getCost() method in order to return the cost of the actor. Each subclass has a different value so I need to be able to distinguish those, but I currently know that I am missing something because even if I change the initial private int cost to some other value it still returns 0. I would appreciate any help.
private int cost = 0;

public int getFoodCost()
    {
        return cost;
    }
danpost danpost

2017/3/24

#
Please show the codes to one of the subclasses.
rockon411 rockon411

2017/3/24

#
All I have currently is
public class Minnow extends Fish
{
    private int cost = 3;

    public Minnow()
    {
        super(1);
    }
and when I test it using this code
public void setUp()
    {
        colony = new Colony();
        nemo = new Minnow();
    }

    public void testGetCost()
    {
        assertEquals(3, nemo.getFoodCost());
    }
it fails and says expected 0.
Super_Hippo Super_Hippo

2017/3/24

#
Remove line 3 in the Minnow class.
rockon411 rockon411

2017/3/24

#
Ok, so how do I designate the value of each subclass since they are all different?
danpost danpost

2017/3/24

#
rockon411 wrote...
Ok, so how do I designate the value of each subclass since they are all different?
public class Minnow extends Fish
{
    public Minnow()
    {
        super(1);
        cost = 3;
    }
and change the first line of code given in this thread to:
protected int cost = 0;
Or, you could add the following in the parent class:
protected void setCost(int value)
{
    cost = value;
}
and in the subclasses
// instead of
cost = 3; // or whatever
// use
setCost(3); // or whatever
rockon411 rockon411

2017/3/24

#
It works now! Thank you so much!
You need to login to post a reply.