Why is the access to a private field not forbidden?

前端 未结 6 2187
無奈伤痛
無奈伤痛 2020-12-21 02:04

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 discu

相关标签:
6条回答
  • 2020-12-21 02:42

    Yes—in Java, private is class private not instance private.

    Many other languages use instance private, eg Ruby and Smalltalk.

    0 讨论(0)
  • 2020-12-21 02:45

    You can access private fields from inside their class. That's the point of having them defined per-class.

    0 讨论(0)
  • 2020-12-21 02:47

    As your main method is in the same class and the instance variable is having private access it is only available to the methods of the same class. there is no access modifier which can restrict the methods of a same class to access its member variable. that is what happening here. if you have your main method in some other class though in the same package it would not have compiled.

    0 讨论(0)
  • 2020-12-21 02:56

    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.

    0 讨论(0)
  • 2020-12-21 03:03

    You can write any other static method in the Person class and access the private variables from that method. Main is just a name. Such is life.

    0 讨论(0)
  • 2020-12-21 03:06

    Because your method main(String[] args) is defined inside the class Person. If the method was defined outside the Person class you would not have been able to do that.

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