0

Lets say I have three classes:

Class A:

public class A {
  private String s;

  public A() {
    s = "blah";
  }

  public void print() {
    System.out.println(s);
  }
}

Class B:

public class B{
  private A a[];

  public B(){
    a = new A[100];
    for (int i=0; i<100;i++) {
      a[i] = new A();
    }
  }

  public void print() {
    for (int i=0; i<100; i++) {
      a.print();  //SHOULD BE a[i].print();
    }
  }
}

Class Main:

public class Main {
  public static void main(String args[]) {
    B b = new B();
    b.print();
  }
}

Why do I get an outputpattern like B@#, where # is a number. I think it has something to do with indirect adressing but im not quite sure. Why doesn't it print out 100 s?

4

1 回答 1

2

您正在打印数组而不是数组中的对象。结果,它打印了对象的地址(数字)和它所属的对象。

我怀疑您想在 B.print() 中调用每个打印件。您还缺少 i 的增量,这意味着它将无限循环。

for(int i = 0; i < 100; ++i)
{
    a[i].print();
}
于 2013-04-28T14:35:41.187 回答