The following code does not compile due to the line marked XX. If the dress() method is changed to be non-static, then this does compile.
Can someone please explain whether this is just because the dress() method doesn’t have access to non-static classes or whether it’s more complicated than that?
public class Wardrobe {
abstract class Sweater {
int insulate() {return 5;}
}
private static void dress() {
class Jacket extends Sweater { // XX
int insulate() {return 10;}
}
}
}
Error message:
java: non-static variable this cannot be referenced from a static context
>Solution :
Your inner class Sweater is not static inside Wardrobe. That means that it requires an instance of Wardrobe.
Inside the static method dress, there is no instance of Wardrobe under consideration, so trying to refer the inner class Sweater causes a compile error.
An easy fix is to make Sweater a static nested class:
public class Wardrobe {
static abstract class Sweater {
int insulate() {return 5;}
}
...
}