开发者

Help applying Classes as fields

开发者 https://www.devze.com 2023-03-28 04:04 出处:网络
What I am trying to do is to implement a constructor of an Object which is a class. I have defin开发者_StackOverflow中文版ed the class in the fields of the class; but because it is a class I dont know

What I am trying to do is to implement a constructor of an Object which is a class. I have defin开发者_StackOverflow中文版ed the class in the fields of the class; but because it is a class I dont know how to initialize it.

here is my class, and the fields.

public class Player
{
// Instance variables.
//Weapon is a class.        
//The max health starts at 30 health points.

  private String myPlayerName;
  private Weapon myWeapon;
  private int myCurrentHealth;
  private int myMaxHealth;
  private int myNumPotions;

/**
 * Constructor initializing class Player
 * Parameters of the player should be:
 * player name, players initial health, the players weapon.
 */
  public Player(String myPlayer, int initialHealth, Weapon currentWeapon) {
      myPlayerName = myPlayer;
      myWeapon = new Weapon();
      myMaxHealth = 30; 
      initialHealth = myMaxHealth;
      myCurrentHealth = initialHealth;
      myNumPotions = 0;       
}

There is something going wrong here, Im not sure what? Can anyone help me construct the currentWeapon parameter?


I'm not entirely sure what you are asking. Your constructor takes in a instance of a Weapon called currentWeapon but you then assign myWeapon to a new instance of Weapon and do not use your currentWeapon that was given to you.

When you construct a Player you should be doing something like:

new Player('blah', 100, new Weapon());

In your Player constructor you should then have the line:

myWeapon = currentWeapon;


Shouldn't it be this? Why are you constructing a new Weapon object instead of assigning the one passed in the constructor argument?

this.myWeapon = currentWeapon;

Update

Construct the Player class this way:-

Player player = new Player("Tom", 10, new Weapon(10,20)); 


try this:

myWeapon = currentWeapon;

or for more cleary:

this.myWeapon = currentWwapon;

it's simple because in OOP, namely C#, Java... object are references, so you don't have to worry. for more specific, check this out !

0

精彩评论

暂无评论...
验证码 换一张
取 消