在TestBook.java文件中,我想用System.out.println(b)
代替许多system.out.println()
行。所以应该在Book类的toString()方法中写什么以返回相同的结果并展现如下:
//Title: xxx
//Author:xxx
//Years:xxx
//Pages:xxx
//edition: xxxx
//==================================
public class Book {
String title;
String author;
int yearOfPublishing;
int numberOfPages;
int eddition;
Book ()
{}
Book ( String title, String author, int yop, int nop, int eddition)
{
this.title = title;
this.author = author;
yearOfPublishing = yop;
numberOfPages = nop;
this.eddition = eddition;
}
public String toString()
{
// return what?? how can i return new lines
}
}
public class TestBook {
public static void main(String[] args) {
Book b = new Book("Data", "Joe", 2015, 276, 3);
System.out.println ( "Title : " +b.title);
System.out.println ( "Author : " +b.author);
System.out.println ( "Year : " +b.yearOfPublishing);
System.out.println ( "Pages : " +b.numberOfPages);
System.out.println ( "Eddition : " +b.eddition);
System.out.println ("==================================");
}
}
.toString()
节省了很多时间 :) - Petro