Java private field access possible when having a reference?

前端 未结 7 1346
野性不改
野性不改 2020-12-19 03:12

I came across the following \"strange\" feature today - if you have a reference to an object from the class A in the body of the class A you can access the private fields of

相关标签:
7条回答
  • 2020-12-19 03:32

    Since f() is a member of Foo, it has the privilege to access the private members of Foo. It's not a surprise to me.

    0 讨论(0)
  • 2020-12-19 03:32

    It makes sense if you consider the intention of the 'private' modifier to hide implementation details.

    Try thinking of it in terms of "this should be private to this class" (which in Java equates to "this should be private to this source file") rather than "this should be private to this instance".

    0 讨论(0)
  • 2020-12-19 03:33

    @Michael's answer is correct. The behaviour is the same for .NET for @asenovm's code.

    In addition , It's same for inner classes as well for Java. Even though you define a variable as private you can access it. I surprised when I encountered at first because it's different for C#.

    public class WrapperClass
    {
    
      public static  class NotThreadsafe {
            private int x = 0;
           //....          
        }
    
        public static void main(String[] args) {           
        final NotThreadsafe nts=new NotThreadsafe(); 
         int x = nts.x ; // !!! THIS IS ACCESSIBLE AS WELL FOR JAVA BUT NOT.NET
        }
    }
    

    This is not same for C# nested classes. If you paste this code to visual studio it doesn't work. Compiler bothers for access levels.

    0 讨论(0)
  • 2020-12-19 03:39

    Because private doesn't mean its private from outside the Object but private from other Classes. You are inside of Foo, therefore you can see bar.

    That way do private Constructors work in Singletons etc.

    0 讨论(0)
  • 2020-12-19 03:45

    Access modifiers work at the class level, not at the instance level: all code in the same class can access private members of all instances of the class.

    Nothing particularly strange about it.

    0 讨论(0)
  • 2020-12-19 03:49

    Those keywords are class-oriented, not object-oriented. So it just looks and sees "oh huh, an object of class Foo is trying to access a private object on Foo. Well, that's fine".

    0 讨论(0)
提交回复
热议问题