how to resolve Non-Static method cannot be referenced from a static context?

Disha picture Disha · Oct 18, 2015 · Viewed 9.1k times · Source
class Base {

    Base show() {
        System.out.println("Base");
        return new Base();
    }

    class Child4 extends Base {

        Child4 show() {
            System.out.println("Child4");
            return new Child4();
        }

    }

    public static void main(String... s) {
        Child4 C1 = new Child4();
        C1.show();
    }

}

Answer

tonio picture tonio · Oct 18, 2015

In your sample, Child4 is a non static inner class of class Base (see here for documentation on inner classes). This means you need an instance of class Base in order to instantiate an object of class Child4.

Since in you example there is no access from the Child4 instance to the outer Base instance, it seems the use of a non static inner class is not intended. You should declare this inner class static, with

static class Child4 extends Base {

This way, the call to new Child4 will be legit from main static context.