开发者

Private member of class accessed in main method

let's assume we have the foll开发者_StackOverflow中文版owing code:

 public class TestScope {
      private int a = 1;
         public static void main(String[] args) {
           TestScope ts = new TestScope();
           ts.a = 6;
           System.out.println(ts.a);
        }
    }

Why at line: ts.a = 6; I can get access to private variable a? I thought that private memebers cannot be accessed outside. I don't underestend this example.


Static methods are still considered part of the class they're declared in, and thus have access to private methods/fields.

If you had the main method (or any other static or instance method) in another class, you would indeed not be able to access a.


It's because a and main(String[]) are both part of the definition of the class TestScope

Private means that a variable or method can only be accessed inside the class definition. The fact that a is an instance variable doesn't mean it can't be accessed by a static public method in the same class.

If the public static void main(String[]) was inside a different class, then it would not be able to access ts's a, because a is hidden from other classes.


A static method is considered 'part' of the class it's in and so has private-scope access to instances of it. This same question was tackled here a couple days ago.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜