Sobes.tech
Junior — Middle

Can an inner class access the private attributes of its outer class?

sobes.tech AI

Answer from AI

Yes, an inner (nested) class in Java can access the private attributes of its outer class. This is because the inner class is part of the outer class and has access to all its members, including private ones.

Example:

public class Outer {
    private int secret = 42;

    class Inner {
        public void reveal() {
            System.out.println("Outer class secret: " + secret);
        }
    }

    public static void main(String[] args) {
        Outer outer = new Outer();
        Outer.Inner inner = outer.new Inner();
        inner.reveal(); // Will output: Outer class secret: 42
    }
}

Thus, the inner class has full access to the private fields and methods of the outer class.

Can an inner class access the private attributes of… - sobes.tech