Reputation: 2674
I've recently picked up Java and have run into a problem. I have several files with different classes, but I can't figure out how I can access objects of the other classes in files other than the one they were declared in. For example:
player.java:
public class Player
{
public static void main(String[] args) {
Player player = new Player();
}
public int getLocation()
{
return 2;
}
}
monster.java:
public class Monster
{
public void attackPlayer()
{
player.getLocation();
}
}
I'm not sure how I can access these objects of other classes effectively from other files and classes themselves? I know I could make the objects static and then access them as variables through the class they were made in, but that seems rather counter-intuitive? I come from a less object-oriented programming background so I'm still trying to understand java's style of programming.
Upvotes: 10
Views: 106915
Reputation: 30957
A class is just a blueprint for an object.
You can only call the methods defined in the Player class on an actual Player object, which you've instantiated - you've done this in the following line in the main(String[] args)
method:
Player player = new Player();
However the player
variable is now only available to code in the scope of its declaration - in this case, anywhere after this line in the main(String[] args)
method.
It's not available outside of this scope. The attackPlayer()
method in the Monster class is most definitely outside of this scope! When you reference player
there, the compiler has no clue what that token refers to. You must pass in an argument of type Player, named player
(or anything you like, really), to that method before you start to call methods on it.
Upvotes: 1
Reputation: 1128
A good place to start would be to pass in the player you want to attack "when" the monster attacks.
battle.java
public class Battle {
public static void main(String[] args) {
Player player = new Player();
Monster monster = new Monster();
monster.attackPlayer(player);
}
}
player.java:
public class Player
{
public int getLocation()
{
return 2;
}
}
monster.java:
public class Monster
{
public void attackPlayer(Player player)
{
player.getLocation();
}
}
Upvotes: 3
Reputation: 1647
You're probably just wanting something like this:
player.java:
public class Player
{
public static void main(String[] args) {
Player player = new Player();
Monster monster = new Monster();
monster.attackPlayer(player);
}
public int getLocation()
{
return 2;
}
}
monster.java:
public class Monster
{
public void attackPlayer(Player player)
{
player.getLocation();
}
}
Hope that helps/makes sense!
Upvotes: 15