1

Trying to understand how to correctly access and pass other objects within a program using java.

In my little program we see the following:

I have a combat class that will need to know the current HP of my hero, which is an instance of my Hero class.

Previously, if another class needed to know the hero's HP, I would simply use a static variable to store HP. I was told this was incorrect usage of static. Below, I created a method in combat for the explicit use of passing the hero into combat. Thus, going forward, any time I need combat to access anything related to my hero object, I can.

Does this make sense? Am I on the right path?

public class Combat
{
   public void passHero(Hero hero1)
   {

   }
}

public class Main
{
    public static void main(String args[])
    {

      Hero hero1 = new Hero();

      //passing hero to Combat
      combat.passHero(hero1);
    }
}

1 Answer 1

2

You are on the right track. When you want to set attributes on an object (in this case the Hero attribute of Combat), that object (Combat) usually provides public methods for setting and retrieving its attributes. You probably want to just create a hero setter on the combat class, or pass the hero in to a constructor

public class Combat
{
   private Hero hero;

   //setter
   public void setHero(Hero hero1)
   {
      this.hero = hero1;
   }

   //constructor
   public Combat(Hero hero1)
   {
      this.hero = hero1;
   }
}

public class Main
{
    public static void main(String args[])
    {

      Hero hero1 = new Hero();

      //passing hero to Combat
      Combat combat = new Combat(hero1);
      //or 
      combat.setHero(hero1);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.