public class BoxDemo1{
public static void main(String args[])
{
box[] a=new box[3];
a[0].width=10;
a[0].length=10;
a[0].color=10;
a[0].dialog="i love you";
System.out.print("a0"+a[0].width);
System.out.print("a0"+a[0].length);
System.out.print("a0"+a[0].color);
System.out.print("a0"+a[0].dialog);
}
}
public static void main(String args[])
{
box[] a=new box[3];
a[0].width=10;
a[0].length=10;
a[0].color=10;
a[0].dialog="i love you";
System.out.print("a0"+a[0].width);
System.out.print("a0"+a[0].length);
System.out.print("a0"+a[0].color);
System.out.print("a0"+a[0].dialog);
}
}
所以要能有结果
System.out.print("a0"+a[1].width);
System.out.print("a0"+a[1].length);
System.out.print("a0"+a[1].color);
System.out.print("a0"+a[1].dialog);
错误仍旧是空指针NullPointer!!!!!
public class BoxDemo1{
public static void main(String args[])
{
box[] a=new box[3];
a[0].width=10;
a[0].length=10;
a[0].color=10;
a[0].dialog="xxxxxxxxx";
System.out.print("a0"+a[0].width);
System.out.print("a0"+a[0].length);
System.out.print("a0"+a[0].color);
System.out.print("a0"+a[0].dialog);
}
}box.java
class box{
public int width;
public int length;
public int color;
public String dialog;
}把他们作为一个工程,编译通过,但是执行工程时却是空指针!
public int width;
public int length;
public int color;
String dialog;
}public class BoxDemo1{
public static void main(String args[])
{
box[] a=new box[3];
a[0]=new box();
a[0].width=10;
a[0].length=10;
a[0].color=10;
a[0].dialog="i love you";
System.out.print("a0"+a[0].width);
System.out.print("a0"+a[0].length);
System.out.print("a0"+a[0].color);
System.out.print("a0"+a[0].dialog);
}
}
对数组的每个元素还要初始化:a[0]=new box();
不过我想这样做并不是没有原因的
比如有一个抽象类abs,有三个类实现了abs,分别是a1,a2和a3
那么就可以
abs[] test=new abs[3];
test[0]=new a1();
test[1]=new a2();
test[2]=new a3();
for(int i=0;i<box.length;i++) {
box[i] = new box();
}