实例化内部类时出现NullPointerException

时间:2014-08-12 22:18:46

标签: java

我知道Java foreach循环只是为了读取值而不是分配它们,但我想知道它们是否可以在对象上调用mutator方法。为了找出我设计的实验。不幸的是,实验崩溃了,我很好奇为什么。

公共课堂考试{

public static void main(String[] args)
{
    foo[] f = new foo[4];
    /*this would be a foreach loop, once I got the program working normally*/
    for(int i = 0; i < f.length; i++) {
        System.out.println(f[i].get());
        f[i].add();
        System.out.println(f[i].get());
    }
}
private class foo {
    foo() {
        int x = 5;
    }

    void add() {
        x++;
    }

    int get() {
        return x;
    }

    private int x;
}

}

当我预期输出为Exception in thread "main" java.lang.NullPointerException时,给出5 6。是因为foo的构造函数没有被调用吗?如果是这样,它怎么称呼?必须要成为静态类吗?

1 个答案:

答案 0 :(得分:0)

你有一个null数组,并且没有初始化数组中的任何Foo项,这意味着它只保留空值。

Foo[] foos = new Foo[4];

// you need to first do this! You need to fill your array with **objects**!
for (int i = 0; i < foos.length; i++) {
  foos[i] = new Foo();  // ******* add this!!*******
  System.out.println(foos[i].get());  // this will now work
  foos[i].add();
  System.out.println(foos[i].get());
}

// now you can use the array

顺便说一下,你的x最初会为0,因为你在Foo构造函数中隐藏变量。

public class Foo {
    private int x;

    Foo() {
        // this **re-declares the x variable**
        int x = 5;
    }

    //....

相反,你想做:

public class Foo {
    private int x;

    Foo() {
        x = 5;
    }

    //....

除了#2:您将需要学习和使用Java命名约定。类名应以大写字母开头,变量名称以小写字母开头。如果您需要其他人(我们!!)快速轻松地理解您的代码,这一点非常重要。


单个班级的一个例子。称之为Foo.java并让它只持有一个类:

public class Foo {
   private int x;

   public Foo() {
      x = 5;

      // not!
      // int x = 5;
   }
   public void increment() {
      x++;
   }

   public void decrement() {
      x--;
   }

   public int getX() {
      return x;
   }

   public static void main(String[] args) {
      int fooCount = 10;
      Foo[] foos = new Foo[fooCount];
      for (int i = 0; i < foos.length; i++) {
         foos[i] = new Foo();
         System.out.println(foos[i].getX());
         foos[i].increment();
         foos[i].increment();
         System.out.println(foos[i].getX());         
      }

      for (Foo foo : foos) {
         foo.decrement();
         foo.decrement();
         foo.decrement();
         System.out.println(foo.getX());
      }
   }
}
相关问题