1

This is the code which I'm trying; I'm getting error on line "outer.inner1.inner2 innerobj2= outerobj.new inner2();".

Can anyone please confirm what is the error and syntax for object creation for nested class methods?

class outer {

  public void outerDisplay() { 
    System.out.println("Statement from outer class");
  }

  class inner {
    public void innerDisplay() {
        System.out.println("Statement from inner class");   
    }
  }

  class inner1 {
    public void inner1Display() {
        System.out.println("Statement from inner1 class");
    }

    class inner2 {
        public void inner2Display() {
            System.out.println("Statement from inner2 class");  
        }
    }
  }
}


public class InnerOuter {

  public static void main(String[] args) {
    outer outerobj=new outer();
    outerobj.outerDisplay();

    outer.inner innerobj=outerobj.new inner();
    innerobj.innerDisplay();

    outer.inner1 innerobj1=outerobj.new inner1();
    innerobj1.inner1Display();

    **outer.inner1.inner2 innerobj2= outerobj.new inner2()**;
    innerobj2.inner2Display();      
  }
}
2
  • new is always first, the qualifying name for class comes after that. so outer.inner innerobj = new outerobj.inner(); Commented Mar 19, 2019 at 20:31
  • Hi @TaaviKivimaa, "outerobj.new inner()" and "outerobj.new inner1()" worked fine. But not working for nested class. Please confirm. Commented Mar 19, 2019 at 20:34

1 Answer 1

2

Class inner2 is an inner class for inner1 not for outer. So to create instance of inner2 you need instance of inner1 like this:

outer.inner1.inner2 innerobj2= innerobj1.new inner2();

or

outer.inner1.inner2 innerobj2= outerobj.new inner1().new inner2();
Sign up to request clarification or add additional context in comments.

1 Comment

thnx Ivan. Worked :)

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.