Inner classes can access even the private members of the outer class.. doesn't it violates the privacy?
Inner classes can access even the private members of the outer class.. doesn't it violates the privacy?
My interviewer asked me about inner classes.. After explaining him everything he stopped me on my one sentence- if inner classes can access private members of outer class then doesn't it violate privacy?
I was unable to answer it.
5 Answers
5
From a JVM perspective, yes, an inner class accessing a private member of the outer class violates privacy.
But, from a Java perspective, no, it does not violate privacy.
The Java Virtual Machine Specification, section 5.4.4. Access Control says:
A field or method R is accessible to a class or interface D if and only if any of the following is true:
[...]
R is private
and is declared in D.
private
So, the JVM will only allow private
members to be accessed from code in the same class, i.e. a nested class cannot access private
members of the outer class.
private
private
The Java Language Specification, section 6.6.1. Determining Accessibility says:
A member (class, interface, field, or method) of a reference type, or a constructor of a class type, is accessible only if the type is accessible and the member or constructor is declared to permit access:
[...]
Otherwise, the member or constructor is declared private
, and access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.
private
So, a private
member in a top-level class and/or nested class is accessible from code anywhere within that top-level class. Since nested classes by definition occur within the body of the enclosing top-level class, code in nested classes can access private
members of the outer class.
private
private
To solve the discrepancy, the Java compiler creates hidden (synthetic) methods for allowing "private" access between closely related classes, i.e. between a top-level class and all its nested classes.
This is an internal trick of the compiler and is not really documented in the specifications. JVMS, section 4.7.8. The Synthetic Attribute says:
[...] A class member that does not appear in the source code must be marked using a Synthetic
attribute, or else it must have its ACC_SYNTHETIC
flag set. [...]
Synthetic
ACC_SYNTHETIC
The Synthetic
attribute was introduced in JDK 1.1 to support nested classes and interfaces.
Synthetic
For more information, do a web search for java synthetic accessor
.
java synthetic accessor
See also: Synthetic accessor method warning
Answer is No
as inner class is part of the outer class, just like other variable and methods are
No
All private
variable/method of a class can be accessed inside all methods of the same class. An inner class is a special case where an instance of InnerClass can exist only within an instance of OuterClass. Hence it has direct access to the methods and fields of its enclosing instance.
private
It is a different class which doesn't have existence without outer class instance
– Ashishkumar Singh
Sep 9 '18 at 10:02
@rishabh jain java compiler injects synthetic accessor methods while compiling. refer my answer above for details
– nits.kk
Sep 10 '18 at 13:58
The answer is NO, because inner class has internal link to the outer class and inner class does not exists without concrecte instance of outer class.
But if you add static to the inner class declaration, it means the it does not have link to the outer class and this is the same, when you declare class in it's own file.
That is all, clear and simple.
nested static class is similar to separate class defined in its own file but not exactly same. Suppose we have a class
Container
which has Nested static class NestedStatic
and an separate class defined in its own file Separate
. Now if we include a reference of type Container
in both NestedStatic
and Separate
then NestedStatic
can access private fileds and methods of Container
but Separate
can not do so`– nits.kk
Oct 4 '18 at 22:26
Container
NestedStatic
Separate
Container
NestedStatic
Separate
NestedStatic
Container
Separate
If you look closely at statement#1
and #2
, you will find that the only difference between them is of one extra object (of inner class) that gets created in #1
, rest everything access-wise is exactly same.
#1
#2
#1
There is no violation because somewhere you're intentionally leaving the door open through some form of access specifier like public
or protected
. Inner class doesn't act (or is not capable to act) as a workaround in there, so no violation absolutely.
public
protected
public class AccessPrivateMemberThruInnerClass
private int getUniqueId()
return 101;
private class AnInnerClass
public int getParentID()
return getUniqueId(); // invokes private method inside a public method.
public int getUniqueIdForce()
return getUniqueId(); // invokes private method inside a public method.
public AnInnerClass getInnerClassObject()
return new AnInnerClass();
public static void main(String args)
AccessPrivateMemberThruInnerClass obj = new AccessPrivateMemberThruInnerClass();
System.out.println(obj.getInnerClassObject().getParentID()); // #1
System.out.println(obj.getUniqueIdForce()); // #2
Answer : No inner class does not voilate the privacy of outer class.
Explanation : All instance methods defined in a class are able to access the private or not private fields and methods defined in the class. This happens as all the instance methods and fields belong to the current object of the class.
Same is true for any inner (non static) class, it has an implicit reference of outerclass current object.
This is the reason as why you can only create the object of inner (non static) class with the help of an object of outer class. If you create the object of inner class inside any instance method of outer class then it is created with the help of implicit current object reference of the outer class.
If you have inner class which is static, then it does not has implicit reference to current object of outer class. Any instance field or method belong to an Object of the class. Hence static inner class can not access any private or non private instance field or method of outer class.
You can set reference of outer container class object explicitly and then it can acess. Now with the help of this explicitly set reference of outer class you can access the private Fields and methods.
So now lets modify the question as why inner static class with an explicit reference of outer class can acess and modify private methods and fields ?
Answer is related to our decision for having such design. The intention of defining any entity within the scope of a class is belongingness. If belongingness is missing then you should reconsider your decision lf making the class as inner (static or non static). Inner classes should be made when we wish to encapsulate a sub responsibility to an entity. This makes the related responsibility still cohesive.
Iterator is a part of any Collection and hence it is inner class. Custom AsyncTask class defined in custom Activity class in android is often made as private static (with weak reference of outer class activity) to prevwnt activity leak as the intention is to modify the fields which are private.
P.S : Afer compiler compiles the code it generates separate files for inner class and you can refer the link to understand as how the interaction of fields of one class being accessible to other class happens when other class is defined as inner class
https://stackoverflow.com/a/24312109/504133 . Actually synthetic getters and setters are injected in the code by compiler so as nested static class can access private fields using these. But still this is backend task done by langauge tools.
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
But isn't inner class a different class in itself? So how can a class access the private member of another class?
– Rishabh Jain
Sep 9 '18 at 9:55