在Java中从类外部调用方法

在Java中从类外部调用方法,java,instance-methods,arrays,class-method,Java,Instance Methods,Arrays,Class Method,这似乎是一个常见的问题,但对于我读到的所有问题,它们似乎处理不同的事情 我正在用一个主类编写一个程序,该主类管理一个不同类的对象数组,我很难从第二个类调用print()方法,从主类内部调用 Main类尝试调用Unit类中的print()。Unit类如下所示: public class Unit{ static int numOfUnits = 0; public Unit[] units = new Unit[8]; private int unitID; //co

这似乎是一个常见的问题,但对于我读到的所有问题,它们似乎处理不同的事情

我正在用一个主类编写一个程序,该主类管理一个不同类的对象数组,我很难从第二个类调用print()方法,从主类内部调用

Main类尝试调用Unit类中的print()。Unit类如下所示:

public class Unit{

    static int numOfUnits = 0;
    public Unit[] units = new Unit[8];

    private int unitID;

//constructors are here

    public void print(){
    for (int i = 0; i < units.length; i++)
    System.out.print(units[i].unitID);
    }

    public void add(Unit unit){
    mobs[numbofUnits] = unit;
    numOfUnits++;
    }
}
公共类单元{
静态整数单位=0;
公共单元[]单元=新单元[8];
私人单位;
//建设者在这里
公开作废印刷品(){
对于(int i=0;i<单位长度;i++)
系统输出打印(单位[i].unitID);
}
公共无效添加(单位){
暴民[人数单位]=单位;
numOfUnits++;
}
}
因此,我希望通过主类向units数组添加新的Unit对象。当我添加完它们(使用Main类中的调用unitToAdd.add(unitToAdd))后,我想从Main中调用Unit的print()方法

我不知道的是,是否以及在哪里使用静态修饰符,如何引用print()方法本身中的变量(也就是说,我是否使用this.unitID、units[I].unitID等等),等等

让我困惑的只是print()方法的性质。我有一些setter和getter可以很好地工作,因为我完全理解调用specificUnit.setID()会更改特定对象的特定变量,但我不知道如何让print()之类的方法工作


谢谢

您可能应该避免在
Unit
中实现
Unit
的列表。您可以通过创建一个
UnitList
类来存储单元列表(可能在
ArrayList
中),然后创建一个
UnitList
实例来避免静态,该实例位于
main
方法的本地

public static void main(String[] argv) {
  UnitList myUnitList = new UnitList();
  myUnitList.add(new Unit(...));
  myUnitList.print();
}
这将跟踪一组单元与单元本身分离开来,避免了难以调试和单元测试的全局可变状态

为了回答您的问题,下面是一组最小的更改,并解释了为什么它们应该是
静态的

public class Unit{

  // static here since every unit does not need to have a number of units.
  static int numOfUnits = 0;
  // static here since every unit does not need to contain other units.
  static Unit[] units = new Unit[8];

  // no static here since every unit does need its own ID.
  private int unitID;

  //constructors are here

  // static here since every unit does not need to know how 
  // to print a particular 8 units.
  public static void print(){
    for (int i = 0; i < numOfUnits; i++)
      System.out.print(units[i].unitID);
  }

  // static here since every unit does not need to know how
  // to add to a global list.
  public static void add(Unit unit){
    mobs[numbofUnits] = unit;
    numOfUnits++;
  }
}
公共类单元{
//这里是静态的,因为每个单元不需要有多个单元。
静态整数单位=0;
//这里是静态的,因为每个单元不需要包含其他单元。
静态单元[]单元=新单元[8];
//这里没有静态,因为每个单元都需要自己的ID。
私人单位;
//建设者在这里
//这里是静态的,因为每个单元不需要知道如何
//要打印特定的8个单位。
公共静态无效打印(){
对于(int i=0;i
简单答案-您需要一个
单元
实例来调用
print()
。我强烈建议你回到基础上来-。

你能从你的主要课程中发布代码吗?你真的想让单元有一个单元数组吗?看起来你可能对如何把事情分组到课堂上感到困惑。如果你想有一个以上的单位,你会考虑到什么情况。“列表”仍然是所有单位的实例共享的。@ Thorbj。如果列表存储在
UnitList
实例中,那么它与
Unit
是完全可分离的,并且不涉及可变静态。@Thorbjørn,是的,我清楚地指出了静态可变状态的问题,并解释了如何解决这些问题。考虑到这一警告,我随后进行了最小的更改,以演示
static
应在何时何地出现,以回答OP实际提出的有限问题。如果你现在还不清楚,我已经考虑到了“你想要一个以上的单元[sic]”时会发生什么,那么我认为不值得进一步讨论。同意-总体上存在一些重大的设计混乱