3

If I declare a variable as private in an inner class, the variable is visible to the outer class. I am unable to understand the logic here. Shouldn't it ideally be only accessible within an inner class?

Nightfirecat
  • 11,432
  • 6
  • 35
  • 51
  • 1
    @wrschneider99 I think this question is different because its asking *why* (making it a language design question) – Paul Bellora Jul 21 '12 at 02:11
  • Ya i was actually questioning the design here. I know its possible to access innerclass variable but i am trying to figure out why would they do the same. – user1527107 Jul 21 '12 at 15:43
  • I think its already asked here...Please do some research before asking. http://stackoverflow.com/questions/1801718/why-can-outer-java-classes-access-inner-class-private-members – Scorpion Oct 17 '12 at 04:10
  • It is so because that's how they designed it. Asking here will yield a lot of guesswork and, if you're lucky, some valid *post hoc* reasoning, but it won't give you the answer. – user207421 Oct 17 '12 at 05:04

1 Answers1

0

I think the answer is subjective as the question basically seems to be asking why Sun/Oracle's language designers decided to allow a certain behavior.

That said, here is an attempt at an answer...

First some terminology, a class declared within a class is a nested class. An inner class is a non-static nested class which must reside within an instance of the outer class. So the inner class is a part of the outer class and in that sense, all members of the inner class are to an extent members of the outer class.

http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.

Another thought is that the valid use cases for an inner class preclude the necessity to allow the inner class to hide members from the outer class. That is, there is no notion that the outer class would not be coupled to the inner class.

Why allow private at all then? Because private members can still be hidden from other classes which may gain access to an instance of an inner class.

Tim Bender
  • 20,112
  • 2
  • 49
  • 58