简体   繁体   中英

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:

java: non-static variable this cannot be referenced from a static context

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;}
    }
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM