访问其他类的对象 [英] Accessing objects of other classes

查看:107
本文介绍了访问其他类的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近拿起了Java,遇到了问题。我有几个文件与不同的类,但我不知道如何可以访问其他类的文件,而不是他们宣布的文件中的对象。例如:

  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();
}
}

我不知道如何访问这些对象的其他类有效地从其他文件和类本身?我知道我可以使对象静态,然后访问它们作为变量,通过他们的类,但这似乎是反直觉的?我来自一个较少面向对象的编程背景,所以我仍然试图理解java的编程风格。

解决方案

可能只是想要这样的:

  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();
}
}

希望有帮助/

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.

解决方案

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!

这篇关于访问其他类的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆