Reputation:
Hi guys Im having trouble creating an instance of a subclass:
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());
}
}
In the line where I create the ComputerLab object in my main function, i am getting the following error:
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)
Can anyone help explain why this error is occuring and how to fix it? Many thanks
Upvotes: 0
Views: 194
Reputation: 24
You can add static in the declaration of the ComputerLab class :
public static class ComputerLab extends Room ...
Upvotes: 0
Reputation: 7326
Your inner class should be static to use it like this. A good use of Nested classes are as as helper classes for a given nesting class.
I'm a personal fan of otherwise separating your classes into separate files.
Upvotes: 0
Reputation: 2399
Because your inner class is not static, it requires an instance of the surrounding class. While there is a way around this, I believe the behavior you are expecting would be from code more like this.
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;
}
}
Upvotes: 0
Reputation: 178521
Your class ComputerLab
is an inner class. In java, an inner class require an instance of the enclosing class - but you don't have one in main()
(it is a static method).
Try changing your inner class to be static
- that means it does not require an instance of the outer class, by changing the definition from:
public class ComputerLab extends Room
to
public static class ComputerLab extends Room
Upvotes: 2