Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Static method with a nested class

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;}
    }
    ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading