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

11,951

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.

Share:
11,951
Admin
Author by

Admin

Updated on June 26, 2022

Comments

  • Admin
    Admin almost 2 years
    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();
        }
    
    }