Can an outer class access members of the inner class?

An inner class is a class defined inside a class, and an inner class can be declared as open, closed, protected. If the inner class, defined as private and protected, can the outer class access members of the inner class? and can internal members access an external class?

+5
source share
5 answers

If an inner class is defined as private and protected, can members of the inner class have access to the outer class?

Yes. These qualifiers only affect the visibility of the inner class in classes that derive from the outer class.

?

, private, .

+13

, ( ). Eclipse:

public class Outer {

  private int x;

  public void f() {
    Inner inner = new Inner();
    inner.g();
    inner.y = 5;
  }

  private class Inner {
    private int y;

    public void g() { x = 5; }
  }    
}

, IDE/ , ( Eclipse " " " → Java → → / → )

+21

" - . , . - , . : -, , . ".

( , " ".)

:, . ( private), ( ) , .

, =).

+1

! , ( ). , ,

InnerClass.staticInnerField 

.

+1

[ ]

.

class Outer {
  private static int x = 0;

  class Inner {
    void print() {
      System.out.println(x); // x can be directly accessed
    } 
  }

  public static void main(String[] args) {
    new Outer().new Inner().print();
  }
}

Even the Outer class can access any field of the Inner class, but through an object of the inner class.

class Outer {
  private class Inner {
    private int x = 10;
  }

  void print() {
    Inner inner = new Inner();
    System.out.println(inner.x);
  }

  public static void main(String[] args) {
    Outer outer = new Outer();
    outer.print();
  }
}
0
source

All Articles