Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
110 views
Welcome To Ask or Share your Answers For Others

1 Answer

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...