Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
395 views
in Technique[技术] by (71.8m points)

java - Why is the access to a private field not forbidden?

For my study in the university I'm forced to do some ugly java basics, like working without encapsulation, main method in the same class etc. (I do not want to open a discussion on a java styleguide, I just want to clarify, that I would not write something like this outside of the university)

I've stumbled across a behaviour that I can't explain to my self:

public class Person {
  // fields
  private int age;

  public static void main(String[] args) {
    Person foo1 = new Person();
    foo1.age = 40;
    System.out.println(foo1.age);
  }
}

Why does this piece of code compile and run without error? How is it possible that I can access the private field? Strange behaviour due to having the main Method in the same class?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Because the static method main is a member of class Person and can thus access any private fields or methods in Person.

What are you worried about? That someone will write a class and then be able to access those methods from their own class?

If you're going to be concerned about anything, be concerned that you can access private fields in any class using reflection but even that's necessary for a lot of useful things.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...