嗨,大家好我在创建子类的实例时遇到了麻烦:
package room;
public class Room {
String roomNumber;
int capacity;
boolean projection;
public Room(String rm, int n, boolean p) {
roomNumber = rm;
capacity = n;
projection = p;
}
public String getRoomNumber() {
return roomNumber;
}
public int getCapacity() {
return capacity;
}
public boolean hasProjector() {
return projection;
}
public class ComputerLab extends Room {
private String os;
public ComputerLab(String rm, int n, boolean p, String os) {
super(rm, n, p);
this.os = os;
}
public String getOS() {
return os;
}
public void setOS(String update) {
os = update;
}
}
public static void main(String[] args) {
Room r;
r = new ComputerLab("G102", 20, true, "WindowsXP");
System.out.println(r.getCapacity());
}
}
在我在main函数中创建ComputerLab对象的行中,我收到以下错误:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - non-static variable this cannot be referenced from a static context
at room.Room.main(Room.java:48)
任何人都可以帮忙解释为什么会出现此错误以及如何解决此问题?非常感谢
答案 0 :(得分:3)
您的班级ComputerLab
是一个内部班级。在java中,内部类需要封闭类的实例 - 但是main()
中没有它(它是静态方法)。
尝试将内部类更改为static
- 这意味着它不需要外部类的实例,方法是更改定义:
public class ComputerLab extends Room
到
public static class ComputerLab extends Room
答案 1 :(得分:1)
因为你的内部类不是静态的,所以它需要一个周围类的实例。虽然有一种解决方法,但我相信您期望的行为将来自更像这样的代码。
public class Room {
protected String roomNumber;
protected int capacity;
protected boolean projection;
public Room(String rm, int n, boolean p) {
roomNumber = rm;
capacity = n;
projection = p;
}
public String getRoomNumber() {
return roomNumber;
}
public int getCapacity() {
return capacity;
}
public boolean hasProjector() {
return projection;
}
public static void main(String[] args) {
Room r = new ComputerLab("G102", 20, true, "WindowsXP");
System.out.println(r.getCapacity());
}
}
class ComputerLab extends Room {
private String os;
public ComputerLab(String rm, int n, boolean p, String os) {
super(rm, n, p);
this.os = os;
}
public String getOS() {
return os;
}
public void setOS(String update) {
os = update;
}
}
答案 2 :(得分:0)
尝试
new Room(...).new ComputerLab(...)
答案 3 :(得分:0)
你的内部类应该是静态的,就像这样使用它。对嵌套类的良好使用与给定嵌套类的辅助类一样。
我个人喜欢将你的课程分成不同的文件。
答案 4 :(得分:0)
您可以在ComputerLab类的声明中添加static:
public static class ComputerLab extends Room ...