Accessing objects of other classes

前端 未结 3 1602
独厮守ぢ
独厮守ぢ 2020-12-09 06:40

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

3条回答
  •  囚心锁ツ
    2020-12-09 07:08

    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!

提交回复
热议问题