简体   繁体   中英

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.

Answer is No as inner class is part of the outer class, just like other variable and methods are

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.

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.

JVM perspective

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 .

So, the JVM will only allow private members to be accessed from code in the same class, ie a nested class cannot access private members of the outer class.

Java perspective

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.

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.

Synthetic access

To solve the discrepancy, the Java compiler creates hidden (synthetic) methods for allowing "private" access between closely related classes, ie 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. [...]

The Synthetic attribute was introduced in JDK 1.1 to support nested classes and interfaces.

For more information, do a web search for java synthetic accessor .

See also: Synthetic accessor method warning

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.

PS : 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.

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.

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 .

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 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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM