【发布时间】:2015-03-29 11:32:18
【问题描述】:
我正在修改我的 Java 书籍,以确保我对对象和 Java 基础知识有深入的了解。我偶然发现了我正在阅读的书中的这段代码Head First: Java 2nd edition (2005)
class Book {
String title;
String author;
}
class Main {
public static void main(String args[]) {
int x = 0;
Book[] myBooks = new Book[3];
myBooks[0] = new Book();
myBooks[1] = new Book();
myBooks[2] = new Book();
myBooks[0].title = "Example title xx";
myBooks[1].title = "Example title cc";
myBooks[2].title = "Example title yy";
myBooks[0].author = "Example author xx";
myBooks[1].author = "Example author cc";
myBooks[2].author = "Example author yy";
while (x < 3) {
System.out.print(myBooks[x].title);
System.out.print(", author ");
System.out.println(myBooks[x].author);
x = x + 1;
}
}
}
我不太明白myBooks[0].title = "Example title xx"的语法
我承认我对数组及其工作方式还不太熟悉,但是循环遍历数组并使用 setter 方法设置所有对象字段不是更好的做法吗?
我认为是这种情况
根据我有限的理解,这种为这些字段分配值的特殊方法与这两个类的范围有关。与您使用静态方法名称的方式相同,而不是首先创建它们各自类的对象,而是使用静态变量。
这看起来很琐碎,但对我来说理解和掌握这个想法很重要。我希望你能帮我清理一下。
【问题讨论】:
-
isn't it a better practice to loop through the array and set all the object fields with setter methods?不,在这种情况下不是。您需要检查迭代变量(例如for (int i = .....)中的i)以了解您当前所在的索引,以设置正确的值。当前使用修复索引的方式在这里更简洁。