2 回答
TA贡献1856条经验 获得超17个赞
技嘉的回答是对的。您应该在 Book 类中为每个字段创建 getter 方法,以便您可以随时单独调用。
您还应该检查 Java 规则和约定,在这种特殊情况下,变量和方法名称应该以小写字母开头,因此您应该从“Available”切换到“available”。
大写字母用于类。
我尝试了您的代码并找到了解决方案,希望它适合您:
这是 BookCollection 类:
public class BookCollection extends ArrayList<Book>{
private static final long serialVersionUID = 1L;
private ArrayList<Book> collection;
public BookCollection() {
this.collection = new ArrayList<Book>();
}
public void addbook(String title, String author, int year, double cost, boolean available) {
Book a = new Book(title, author, year, cost, available);
this.add(a);
}
public static void main(String[] args) {
BookCollection library = new BookCollection();
library.addbook("Pride & Prejudice", "Jane Austen", 1801, 24.95, true);
System.out.println(library.get(0).isAvailable());
}
}
这是 Book 类,带有 getter 和 setter:
public class Book {
private String name;
private String author;
private int year;
private double cost;
private boolean available;
public Book(String name, String author, int year, double cost, boolean available){
this.name = name;
this.author = author;
this.year = year;
this.cost = cost;
this.available = available;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public double getCost() {
return cost;
}
public void setCost(double cost) {
this.cost = cost;
}
public boolean isAvailable() {
return available;
}
public void setAvailable(boolean available) {
this.available = available;
}
}
添加回答
举报