-2

I have 3 classes, Main, Enemy and UserCharacter. Enemy contains the enemy's attributes and possible actions. UserCharacter contains the user's attributes and possible actions. Main manages the logic and creates the objects from Enemy and UserCharacter classes.

I'm trying to use a setter method contained in class Enemy from a method in class UserCharacter

public class UserCharacter {

    private String userName = "Adventurer";
    private int userAttack = 5;
    private int userLife = 100;

    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }

    public int getUserLife() {
        return userLife;
    }
    public void setUserLife(int userLife) {
        this.userLife = userLife;
    }


    public void Attack() {          
        Enemy.setEnemyLife(10);                 
    }    
}

Is there a way to do so without setting the method as static? (other than creating an object of the class which is not an option since it's done in Main) Is using a static setter method advisable? (and I guess I'll have to create a dummy static variable for the setter)

Thanks

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373

1 Answers1

2

You're asking an XY Problem where you're looking at the problem in the wrong way. The issue is not that you want to call a setter without creating an instance, but rather what you want to do is call the setter on the correct instance, meaning that

  1. No you don't want to call an instance method without an instance -- I'm afraid that this makes no sense at all
  2. And yes, you're right, making the setter static would not help, since then each Enemy would share the same state -- not good.
  3. No you do not want to create a "dummy" instance (what good would it be to change the state of something that you're not using?)
  4. You do need to pass a reference of the correct Enemy instance to where the method needs to be called and then call the method on that instance. The key to understanding what's going on is that the character is not just fighting any Enemy but rather it is fighting a specific Enemy, one determined by your Game, and you need to change the state of both that character and that specific Enemy as the attack/fight occurs. So changing the state of a dummy enemy, or all enemies (via static) makes no sense. It has to be that specific enemy object, which is why you need a reference to that object where needed, and call the method on that object.

In this setting, I would create a Game or World class that handles interactions and clashes between enemies and characters. When a character attacks an enemy, it tells this World class that it is doing so, and which enemy, and the World object then determines what points to add or deduct from the character and the enemy.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373