我编写了一个简短的脚本来了解 Java 数组:
class Dog {
String name;
void bark() {
System.out.println(name + " is barking");
}
void eat() {
System.out.println(name + " is eating");
}
}
class mypets {
public static void main(String [] args) {
Dog dogA = new Dog();
dogA.name="Lassy";
dogA.bark();
dogA.eat();
Dog[] myDogs = new Dog[3];
myDogs[0].name = "Barney";
myDogs[0].bark();
}
}
然后我编译并运行我的程序:
C:\Java>javac mypets.java
C:\Java>java mypets
Lassy is barking
Lassy is eating
Exception in thread "main" java.lang.NullPointerException
at mypets.main(mypets.java:22)
我做错了什么?我试着用谷歌搜索那个可怕的“java.lang.NullPointerException”,但老实说我现在很困惑。