因此,我有三个班级:books,booksOut和Allbooks。 booksout和Allbooks是扩展类/是书籍的子类。但是我有一个问题/问题:
我从toString方法的allBooks中得到一个错误。说出bookID等(即book中的所有变量)设置为private。我被告知您应该始终避免使用公共变量,因此我很犹豫。还有另一种方法吗?还是将它们公开是处理此问题的最简单/最佳方法?
这是代码:
图书
public class books {
private int bookID;
private String title;
private String author;
public books() {
}
public books(int bookID, String title, String author) {
this.bookID = bookID;
this.title = title;
this.author = author;
}
public int getBookID() {
return bookID;
}
public void setBookID(int bookID) {
this.bookID = bookID;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String addSpaces(String s, int w) {
String spc = "";
for (int i = 1; i <= (w - s.length()); i++) {
spc = spc + " ";
}
return spc;
}
public class AllBooks extends books{
private String genre;
private String status;
private String Location;
private String condition;
全书
public AllBooks(int bookID, String title, String author, String genre, String status, String Location, String condition ) {
super(bookID, title, author);
this.genre = genre;
this.status = status;
this.Location = Location;
this.condition = condition;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getLocation() {
return Location;
}
public void setLocation(String Location) {
this.Location = Location;
}
public String getCondition() {
return condition;
}
public void setCondition(String condition) {
this.condition = condition;
}
@Override
public String toString() {
String stg = "";
stg = stg + bookID + '\t' + title + addSpaces(title, 30) + author + addSpaces(author, 30) + genre + addSpaces(genre, 15) + status + addSpaces(status, 5) + Location + addSpaces(Location, 20) + condition;
return stg;
}
public String toString(int i){
String stg = "";
stg += bookID + "#" + title + "#" + author + "#" + genre + "#" + status + "#" + Location + "#" + condition + "#";
return stg;
}
聚苯乙烯
抱歉,这是一个愚蠢的问题。这是一个学校项目,应在我现在放假后放学,这就是我不问老师的原因。我确实在网上检查了答案,但是我遇到的教程并没有过多提及礼节。感谢您的帮助,和/或抱歉浪费您的时间。
最佳答案
使用现有的公共访问器。例如,在子类中使用getBookID()
而不是尝试直接访问超类的私有字段。
@Override
public String toString() {
String stg = getBookID() + '\t' + getTitle()
+ addSpaces(title, 30) + getAuthor()
+ addSpaces(author, 30) + getGenre()
+ addSpaces(genre, 15) + getStatus()
+ addSpaces(status, 5) + getLocation()
+ addSpaces(Location, 20) + getCondition();
return stg;
}
另一种选择是将字段设置为
protected
。但是,这允许任意数量的子类直接耦合到超类的表示形式。通常最好将数据封装在方法后面。顺便说一句,您可能会发现String.format()有用。有关语法,请参见Format String Syntax。
关于java - 继承和私有(private)/公共(public)变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17681184/