public class Book { String title; String author; class BooksTestDrive { } public static void main(String [] args) { Book [] myBooks = new Book[3]; int x = 0; myBooks[0].title = "The Grapes of Java"; myBooks[1].title = "The Java Gatsby"; myBooks[2].title = "The Java Cookbook"; myBooks[0].author = "bob"; myBooks[1].author = "sue"; myBooks[2].author = "ian"; while (x < 3) { System.out.print(myBooks[x].title); System.out.print( "by" ); System.out.println(myBooks[x].author); x = x + 1; } } }
为什么没有提示错误,运行的时候却有问题呢?
对数组的初始化工作没有结束,在Java中对非基本数据初始化时,必须使用new。在使用new创建数组后,此时数组还是一个引用数组。只有再创建新的对象,并把对象赋值给数组引用,到此初始化结束。
public class Book {
String title;
String author;
public static void main(String [] args) {
Book[] myBooks = new Book[3];
myBooks[0] = new Book();
myBooks[1] = new Book();
myBooks[2] =new Book();
myBooks[0].title = "The Grapes of Java";
myBooks[1].title = "The Java Gatsby";
myBooks[2].title = "The Java Cookbook";
myBooks[0].author = "bob";
myBooks[1].author = "sue";
myBooks[2].author = "ian";
for(int x = 0; x < 3; x++ ){
System.out.print(myBooks[x].title);
System.out.print( " by " );
System.out.println(myBooks[x].author);
}
}
}