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

2017/3/11

I have an actor that is being instantiated by another actor (not created), i want to reference the actor that's doing the instantiating

Dylex Dylex

2017/3/11

#
Hi, in C# i think i would usually just pass the object as a reference, but that can't seem to be done in Java. I've got a class called "Fists", it is a weapon and in order to work will need a reference to the object that it has been instantiated by (the player in this example). I am not sure how to do this. Here is an image of my class hierarchy: https://i.gyazo.com/1ccedc6894f9f9701ebe5c877fb652cd.png I create an instance of Fists for my Player actor, fists is a subclass of Weapon, the instance i create in my player actor is of type Weapon. Any help is greatly appreciated!
danpost danpost

2017/3/11

#
If Player objects are the only ones to own Fists objects, then from a design perspective, it is better to place the Fists class inside the Player class:
public class Player extends Actor
{
    // constructor and methods for players

    private class Fists extends Weapon
    {
        // constructor and methods for fists
    }
}
As a private inner class, only a Player object can create a Fists object and the Fists object knows its owner:
Player owner = Player.this;
You can have the Fists object remove itself from the world if ever the owner is removed:
// in act method of Fists (or method called by it)
if (Player.this.getWorld() == null) getWorld().removeObject(this);
Dylex Dylex

2017/3/11

#
Hi Dan, thanks for replying. My fists class will be used by other actors, such as an enemy, so i don't really want to put it as a subclass of my Player.
danpost danpost

2017/3/11

#
Dylex wrote...
My fists class will be used by other actors, such as an enemy, so i don't really want to put it as a subclass of my Player.
Well then, you do still do similarly by subclassing the Fists class in each class they are used for. So, instead of 'private class Fists extends Actor' in Player class, you could use 'private class PlayerFists extends Fists'.
Dylex Dylex

2017/3/11

#
Hmm, i was just thinking it might be better to just set the location of the Fists actor to that of my Player every time i shoot. I'm just thinking that it might be a bit pointless to have classes for each weapon type in my character that inherits from other weapon classes, might as well just have individual classes for each actor.
You need to login to post a reply.