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

2017/3/30

Overriding a Method

rockon411 rockon411

2017/3/30

#
I have an injured method in a parent class that removes the object once their health gets to zero. I have one subclass that needs to injure those around it before it is removed from the world. I would like to override the parent class injure method is there anything special I need to do because I created another injure method in the subclass and it still seems to be using the parent class one.
danpost danpost

2017/3/30

#
rockon411 wrote...
I have an injured method in a parent class that removes the object once their health gets to zero. I have one subclass that needs to injure those around it before it is removed from the world. I would like to override the parent class injure method is there anything special I need to do because I created another injure method in the subclass and it still seems to be using the parent class one.
Please show the codes for the methods in both classes and the codes from where you are calling them. Indicate which class the methods and calls are located in.
rockon411 rockon411

2017/3/30

#
This is in my parent class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
private int health = 0;
 
public Fish(int lives)
    {
        super();
        this.health = lives;
    }
public void injure(int injury)
    {
        health = health - injury;
        if (health <= 0)
        {
            Island island = (Island) getWorld();
            island.remove(this);
        }
And this is in my subclass
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
private int health = 1;
public Eel()
    {
        super(1);
    }
public void explode()
    {
        for (Object obj : getNeighbors(1, true, Shark.class))
        {
            getWorld().remove((Shark)obj);
        }
        getWorld().remove(getOneIntersectingObject(Shark.class));
    }
public void injure(int injury)
    {
        health = health - injury;
        if (health <= 0)
        {
            electrocute();
            Island island = (Island) getWorld();
            island.remove(this);
        }
    }
danpost danpost

2017/3/30

#
For one thing, you need to remove line 1 from the Eel class. Then, what code do you have for the 'electrocute' method?
rockon411 rockon411

2017/3/30

#
Whoops I meant to change the explode() method to electrocute(), so that's the code. Also when I remove the first line then the new injure method has an error "health has private access in Act."
danpost danpost

2017/3/30

#
rockon411 wrote...
Whoops I meant to change the explode() method to electrocute(), so that's the code. Also when I remove the first line then the new injure method has an error "health has private access in Act."
Change the access to health in the Fish class to 'protected' instead of 'private'.
rockon411 rockon411

2017/3/30

#
Thanks!
You need to login to post a reply.