java – Doesn't the outer class have access to the members of the nested class

Question:

Please help me figure it out. Schildt writes in his book that "… a nested class has access to the members of its outer class. BUT (Warning!) The outer class does not have access to the members of the inner class ." And here the question is – what exactly was meant? as it does not have access when, in the example below, a method of an outer class accesses a member of its inner class without issue.

class VneshnClass {

    void test (){
        VnutrClass vnutObj = new VnutrClass ();
        vnutObj.vnutr_x++; // этим методом внешнего класса меняем значение 
                           // поля внутреннего класса
        vnutObj.displayVn();
    }

    class VnutrClass {  // внутренний класс
        int vnutr_x = 33;  // вот наше поле внутреннего класса

        void displayVn(){  // метод вложенного класса
            System.out.println("vnutr_x = "+vnutr_x);
        }
    }
}

class MainClass {
    public static void main (String [] args){
        VneshnClass obj = new VneshnClass();
        obj.test();
    }
}

Answer:

Schildt should have given an example. Here's what I mean:

class Outer {
    int outer_х = 100;

    class Inner {
        int inner_x = 200;

        void displayOuter () {
            System.out.println(outer_х); // вложенный класс имеет внешний. нормально
        }
    }

    void displayInner() {
        System.out.println(inner_х);  // ошибка. внешний класс не имеет доступа к членам вложенного класса 
    }

}

Access to members of a nested class is possible only through a reference to an instance of the nested class.

Inner inner = new Inner(); 
println(inner.inner_x);
Scroll to Top