访问类和创建对象

时间:2014-03-23 19:34:44

标签: java class

我试图访问一个名为" Person"它只有一个参数," name"这是我的班级:

class person{
  String name;
   public void setName(String name){ this.name = name; }
   public String getName(){ return name; }
  }

然后在我的主要课程中,我得到了以下内容:

public class exercise{
   public static void main(String []args){
   Person person [] = new Person [20];
   person[0].setName("zgur");
   System.out.printf(""+person[0].getName());
  }
}

我收到错误:线程中的异常" main"显示java.lang.NullPointerException

我缺少什么和/或做错了什么?

感谢。

3 个答案:

答案 0 :(得分:2)

您正在创建一个数组但不填充对象。想想一个像蛋箱一样的参考类型。在你用鸡蛋填满之前,你不能使用箱子里的任何鸡蛋。

所以改为:

// note that class names should begin with an uppercase letter
public class Exercise{
   public static void main(String []args){
     Person[] people = new Person [20];
     for (int i = 0; i < people.length; i++) {
       people[i] = new Person();       }
     people[0].setName("zgur");
     System.out.printf("" + people[0].getName());
   }
}

如果这是我的代码,我考虑使用ArrayList<Person>,只在需要时添加一个Person。例如

public static void main(String[] args) {
  List<Person> personList = new ArrayList<Person>();
  personList.add(new Person("Stan"));  // assuming that a String constructor exists
  personList.add(new Person("Bill"));
}

答案 1 :(得分:2)

您需要以下内容:

Person[] people = new Person[20];
people[0] = new Person("Harry");
people[1] = new Person("Alan");
...etc.

答案 2 :(得分:2)

请注意,此处您不创建Person实例:

  

人[] =新人[20];

在这里,您可以创建一个包含20个引用的数组,但每个引用都使用 null 进行初始化。 所以访问zeroe的元素为

  

人[0] .setName( “zgur”);

你正在获得NPE。

如果您确实需要使用数组来处理Person实例,请确保已初始化您要处理的项目:

  

person [0] = new Person();

     

人[0] .setName( “whateverYouNeed”);

请注意:最好使用以下形式的数组创建:

  

人[]人=新人[20];

在引用类型后面带[]。

相关问题