Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the access to a private field not forbidden?

Tags:

java

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?

like image 393
citronas Avatar asked Nov 28 '22 01:11

citronas


2 Answers

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.

like image 80
cletus Avatar answered Nov 29 '22 15:11

cletus


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

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

like image 29
akuhn Avatar answered Nov 29 '22 15:11

akuhn