1

I've encountered one interesting thing to me relating to the basics of Java. Here's the code:

class Whoa {
  private int n;

  private void d() {
    Whoa whoa = new Whoa();
    whoa.n = 1;
  }
}

Why the field n of object whoa is accessible? I mean, OK, we're in the class. But whoa is the separate object, I thought we have access only to the fields of a current object. Although I admit that if we have a method that takes a Whoa parameter:

private void b(Whoa w) {
  w.n = 20;
}

we'll definitely have access to n. It's all quite confusing. Could anyone clarify this please?

iozee
  • 1,339
  • 1
  • 12
  • 24

3 Answers3

6

The point of Java's access modifiers is protecting the internals of a class from code foreign to it. Since all instances of the same class share the same internal code, there would be little use in enforcing access restriction between them.

This the rationale of Java's class-level encapsulation.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
0

As long as your are in the same class,you can access the private variables

SpringLearner
  • 13,738
  • 20
  • 78
  • 116
0

For every new instance of the Object 'Whoa' that you create there will be an instance of 'n'. That 'n' can only be accessed from the instance of 'Whoa' (hence private)

msam
  • 4,259
  • 3
  • 19
  • 32