我了解了JAVA基本级别。然后,我遇到了一些问题...没有创建内部类实例。
public class example {
class book {
private String name = null;
private int page = 0;
book(String name, int page) {
this.name = name;
this.page = page;
}
String getName() {
return this.name;
}
int getPage() {
return this.page;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
book b1 = new book("book1", 300); // this line is making an error
System.out.println(b1.getName());
System.out.println(b1.getPage());
System.out.println();
}
}
答案 0 :(得分:1)
您的book
类是您的example
类的内部类,这意味着它需要一个封闭的example
类实例才能实例化(new example().new book("book1", 300)
)。 / p>
但是,将book
类设为非嵌套将更有意义:
class book {
private String name = null;
private int page = 0;
book(String name, int page) {
this.name = name;
this.page = page;
}
String getName() {
return this.name;
}
int getPage() {
return this.page;
}
}
public class example {
public static void main(String[] args) {
book b1 = new book("book1", 300);
System.out.println(b1.getName());
System.out.println(b1.getPage());
System.out.println();
}
}