I have a class called GreenhouseControls that has a bunch of
classes built into it such as:
public class ThermostatNight extends Event {
public ThermostatNight(long delayTime) {
super(delayTime);
}
public void action() {
// hardware control code here.
thermostat = "Night";
}
public String toString() {
return "Thermostat on night setting";
}
}
I pull values from a text file to get event names such as "ThermostatNight" and time values such as "2000". To instantiate a new object with those values I built a EventFactory that accepts the values as arguments.
This is the class I have built to create new event objects from text file values:
public class EventFactory{
public static Event createSpecificEvent(String eventName, long delayTime) {
Event event = null;
switch(eventName) {
case "ThermostatNight":
event = new ThermostatNight(delayTime); // Compiler error
break;
case "ThermostatDay":
event = new ThermostatDay(delayTime);
break;
case "LightOn":
event = new LightOn(delayTime);
break;
case "LightOff":
event = new LightOff(delayTime);
break;
...
}
}
Everything was working well when I ran the program until I pulled the EventFactory class out of GreenhouseControls and into it's own independent class. Now I am getting a compile time error that says:
"No enclosing instance of type GreenhouseControls is accessible. Must qualify the allocation with an enclosing instance of type GreenhouseControls (e.g. x.new A() where x is an instance of GreenhouseControls)."
See in-line comment in EventFactory class to see where the error occurs at "new ThermostatNight(delayTime)"
Your classes are currently inner classes, which need to be constructed in the context of instances of the containing class. Your options are:
static
classes, at which point they won't be inner classes any morePersonally I'd go for the last option if possible - nested classes can be useful at times, but you should only use them when there's a real benefit. There are various restrictions which can be quite subtle and which are best avoided if possible. Do you have any compelling reason to make these nested classes?
See more on this question at Stackoverflow