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

2011/12/10

Accessing a subclass method from the superclass (sort of)

darkmist255 darkmist255

2011/12/10

#
I don't really know how to title it, but this is my problem. In my PlayerShotPlain class (the actor for the projectile the player shoots) I have the following method
    private void checkHitEnemy()
    {
        if(getOneIntersectingObject(Enemy.class) != null)
        {
            enemy = (Enemy) getOneIntersectingObject(Enemy.class);
            enemy.damageEnemy(1 * stats.damageLevel);
        }
    }
When I try to compile it says "cannot find symbol - method damageEnemy(double)". I believe this is because "Enemy.class" is not actually anything, it is just the superclass for all of the enemies. I thought that when I got the intersecting object it would return the specific type of enemy. I see three solutions: 1. Figure out how to make it find the specific type of enemy and damage it 2. Make multiple if statements, one for each type of enemy (which would add versatility) 3. Make a new superclass called "Projectiles" that will hold this method, then each type of shot doesn't need the method. I'm going to work on solution 3, but if solution 1 is possible, please tell me :D!
davmac davmac

2011/12/10

#
Just add the method to your Enemy class: public void damageEnemy(double damage) { } Then you can override it in the subclasses. When you call it on an object whose type is a subclass of Enemy, it will call the version defined in the subclass.
darkmist255 darkmist255

2011/12/10

#
Thanks! I had already done solution 3, but I commented it out and added in that method. Now it's:
    public void damageEnemy(double amount)
    {
        //this class must be overridden in the actor
    }
Works much nicer :D!
AwesomeNameGuy AwesomeNameGuy

2011/12/11

#
It kinda does return the specific type of enemy in a way. It will return the specific type of enemy object at runtime alright, but the compilor doesn't know what subclass of enemy it's going to get when it compiles the program, hence it will only let you use methods that are defined in the enemy superclass in your code, unless you cast it to a more specific type, and you should only do that if you have a situation where you know for sure what kind of enemy you are going to get, otherwise I believe it causes a run time error. That aside, at runtime java will know which subclass it has though, and it will use the correct method if it's overridden. If that makes sense.
You need to login to post a reply.