确切地说,您可以使用静态变量。但是,与其在 toString() 方法 id 中增加它,不如在构造函数中增加它,因为您的问题建议您要计算对象的数量,而不是在您的对象实例之一上调用 toString() 方法的次数。
public class Book {
private static int i = 0;
public Book(){
i++;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append("\n\n-Buch"+ i +": ");
result.append("\nTitel: " + this.Titel + "§ ");
result.append("\nAuthor: " + this.Autor + "§ ");
return result.toString();
}
}
编辑:下面的评论是正确的,这将始终打印出在您调用任何 Book 对象的 toString() 方法时已经创建了多少本书。
这是第二个版本,现在每个对象实例都有一个变量,用于根据创建时间和上面的相同静态变量来标识书籍编号,请查看示例输出。
public class Book {
private static int i = 0;
private int i2;
public Book() {
i2 = i;
i++;
// or place 'i2 = i;' here if you want to start with "Book 1 of..."
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append("Book " + i2 + " of " + i + " books in total");
return result.toString();
}
}
样品电话:
public class SampleCall{
public static void main(String[] args) {
Book b = new Book();
Book b1 = new Book();
Book b2 = new Book();
Book b3 = new Book();
System.out.println(b1);
System.out.println(b1);
}
}
样本输出:
Book 0 of 4 books in total
Book 1 of 4 books in total
由于您刚刚开始使用 Java,请考虑一个解决方案,您可以自己设置每个 Book 实例的数量以完成:
public class Book {
private static int i = 0;
private int bookNumber;
public Book(int bookNumber) {
i++;
/* this.bookNumber means "the variable of the currently in creation book object instance)
* you only need it if its not clear because there is a local variable with the same name
*/
this.bookNumber = bookNumber;
}
// a second (default) constructor in case you want to create book objects and dont yet know the number of it
// after creation you can use the get/set values to access the variable from "outside"
public Book(){
i++;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
// Here you dont need this because there is no local variable bookNumber
// You can however always use it when referencing such object variables
result.append("Book " + bookNumber + " of " + i + " books in total");
return result.toString();
}
public int getBookNumber(){
return bookNumber;
}
public void setBookNumber(int bookNumber){
this.bookNumber = bookNumber;
}
}
样品电话:
public class SumeMain {
public static void main(String[] args) {
Book b = new Book(1);
Book b1 = new Book(2);
Book b2 = new Book();
System.out.println(b);
System.out.println(b1);
//Note below book not yet has a number:
System.out.println("Forgotten book: "+b2);
//But you can set it from "outside" (here)
b2.setBookNumber(3);
System.out.println(b2);
//Also note you now took controll of those numbers so two books can have the same number:
b2.setBookNumber(2);
System.out.println("Duplicate book number: "+b2);
}
}
样本输出:
Book 1 of 3 books in total
Book 2 of 3 books in total
Forgotten book: Book 0 of 3 books in total
Book 3 of 3 books in total
Duplicate book number: Book 2 of 3 books in total
通过这样的例子,我认为你是学习语言基础知识的最佳方式,跟上并玩得开心:)