Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

I observed that Outer classes can access inner classes private instance variables. How is this possible? Here is a sample code demonstrating the same:

class ABC{

    class XYZ{

        private int x=10;

    }

    public static void main(String... args){

        ABC.XYZ xx = new ABC().new XYZ();

        System.out.println("Hello :: "+xx.x); ///Why is this allowed??

    }

}

Why is this behavior allowed?

1 Answer

0 votes
by (46k points)

The inner class is just a way to cleanly separate some functionality that really belongs to the original outer class. They are intended to be used when you have 2 requirements:

  1. Some piece of functionality in your outer class would be most clear if it was implemented in a separate class.
  2. Even though it's in a separate class, the functionality is very closely tied to way that the outer class works.

Given these requirements, inner classes have full access to their outer class. Since they're basically a member of the outer class, it makes sense that they have access to methods and attributes of the outer class -- including privates.

Related questions

0 votes
1 answer
asked Jul 29, 2019 in Java by Suresh (3.4k points)
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.5k questions

29.9k answers

500 comments

99.1k users

Browse Categories

...