2
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();
    }

}
3
  • Hi Disha. Welcome to stack overflow. Please make it easier to understand your question: What do you try with the code you posted? Do you get an error message, or does the code behave differently than you think it should? What do you think it should do, and what behavior did you observe? Commented Oct 18, 2015 at 11:59
  • Don't nest the Child4 class into the Base class. Use 2 different files: one for each class. Commented Oct 18, 2015 at 12:14
  • Possible duplicate of non-static variable cannot be referenced from a static context Commented Oct 18, 2015 at 12:30

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

You can do this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.