Does ParentClass.NestedClass nc = new NestedClass (); implicitly create an instance of the parent class?

I have a code from a tutorial:

public class Question_3_4 {
  public static class Inner {
    private void doIt() {
      System.out.println("doIt()");
    }
  }
  public static void main(String[] args) {
    Question_3_4.Inner i = new Inner();
    i.doIt();
  }
}

Well, the Inner class is static, so I assume that the above code implicitly creates an instance of Question_3_4?

Question_3_4.Inner i = new Question_3_4.Inner();

gives the same result as the code above.

So I guess

  Question_3_4.Inner i = new Question_3_4.Inner();   

and

  Question_3_4.Inner i = new Inner();

- same.

If my assumption is false, what am I missing here?

+4
source share
3 answers

First, you are not using the correct terminology.

You have not declared an inner class, but a static nested class.

: : . , , . .

, Java Nested Classes:

:

, Inner , , Question_3_4?

static.
, , , .

( static ).

, static , Question_3_4.Inner i = new Inner();, , .

public class Question_3_4 {

     public class Inner {
             private void doIt() {
                     System.out.println("doIt()");
             }
     }
     public static void main(String[] args) {
             Question_3_4.Inner i = new Inner(); 
             ^--- error: non-static variable this cannot be referenced from a static context              
             i.doIt();
     }

}
+3

( , partent )... ...

, , , ...

public class Calculator {
    public Calculator() {
        System.out.println("Hello Constructor Calc");
    }

    public static class Inner {
        private void doIt() {
            System.out.println("doIt()");
        }
    }

    public static void main(String[] args) {
        Calculator.Inner i = new Inner();
        i.doIt();
        Calculator.Inner i2 = new Calculator.Inner();
        i2.doIt();
    }
}

i2

Doit()

Doit()

+2

. .

. . .

. ( ), . , , .

.

A . ( ) , . .

To create an instance of an inner class, you must first create an instance of the outer class. Then create an internal object inside the external object using this syntax:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();
+1
source

Source: https://habr.com/ru/post/1682987/


All Articles