来自另一个类中对象的引用变量

时间:2014-10-07 03:42:24

标签: java

我有两个班,一个名为" Territory"用以下变量构造一个对象:" posX"和" posY",像这样:

public Territory(int column, int row)
{
    posX = column;
    posY = row;
}

然后在另一个班级,"世界"我做了以下事情:

Territory territory1 = new Territory(0, 0);

但是当我尝试从该对象引用一些变量时,例如:

System.out.println("Coordinates: " + territory1.posX);

我收到错误:

cannot find symbol - variable territory1

任何帮助?

编辑:

以下是完整的课程:

地区:

public class Territory
{
    public int posX;
    public int posY;
    public int armies;
    public String owner;

    public Territory(int column, int row)
    {
        posX = column;
        posY = row;
        armies = 0;
        owner = null;
    }
}

世界:

public class World
{
    public World()
    {
       Player player1 = new Player();
       Player player2 = new Player();

       Territory territory1 = new Territory(0, 0);
       Territory territory2 = new Territory(1, 0);
       Territory territory3 = new Territory(0, 1);
       Territory territory4 = new Territory(1, 1);     
    }

    public java.lang.String toString()
    {
        System.out.println(territory1.getposX);
    }
}

2 个答案:

答案 0 :(得分:2)

您的toString()方法无法识别' territory1'因为它是在另一种方法中声明的

这应该有效

public class World
{
     Territory territory1, territory2, territory3, territory4;

    public World()
    {
       Player player1 = new Player();
       Player player2 = new Player();

       territory1 = new Territory(0, 0);
       territory2 = new Territory(1, 0);
       territory3 = new Territory(0, 1);
       territory4 = new Territory(1, 1);     
    }

    public toString()
    {
        if( territory1 != null)
            System.out.println(territory1.posX);
    }
}

答案 1 :(得分:0)

如果您无法访问另一个类中的类的属性,则表示该类对该类不可见。检查访问说明符以获取属性。您可能必须使用getter(公共方法来获取私有变量的值)。