【发布时间】:2018-06-28 14:08:30
【问题描述】:
为什么不能正确编译?我添加了 main 方法行以尝试对其进行测试,但是我得到了很多错误,除了说它们不是语句之外,还说私有构造函数是表达式的非法开头以及公共构造函数。它还要求我在我认为不必要的地方添加分号,因为它们是方法的开始。我不希望有人为我重新输入代码,但至少有人能指出我正确的方向并告诉我哪里出错了吗?
import java.util.Arrays
public class Book{
public static void main (String[] args) {
private String title;
private String authors[];
public Book() {
title = "Test";
authors = null;
}
public Book(String title, String[] authors) {
this.title = title;
this.authors = authors;
}
public String getterTitle() {
return title;
}
public void setterTitle(String title) {
this.title = title;
}
public String[] getterAuthors() {
return authors;
}
public void setterAuthors(String[] authors) {
this.authors = authors;
}
public String bookToString() {
return "" + getterTitle() + " by " + getterAuthors() + "";
}
}
【问题讨论】:
-
您的导入行末尾似乎缺少分号。
-
为了澄清一些术语,您有私有的成员变量,也称为字段。这些不是构造函数。构造函数是
public Book()...和public Book(String title, String[] authors)...。您可以发现这些,因为它们与类同名。 -
请注意,“表达式的非法开头”意味着错误位于错误指示的行之前。
-
在这种情况下,
main()的右大括号}将解决其中一个答案中所述的问题。
标签: java constructor private getter-setter