-3

I am studying for the OCA Exam and came across this code:

public class Driver {

  private void printColor(String color) {
    color = "purple";
    System.out.print(color);
  }

  public static void main(String[] args) {
    new Driver().printColor("blue");
  }
}

The question asks "What is the outcome of this piece of code". I initially thought it will be "it does not compile" because you have an object instance trying to access a private method. But, it turns out to be "purple".

Why is it "purple" and not "it does not compile"? I know the Driver instances lives in the same class it is declared in, but why it still have the privilege to access private methods?

Thank you

Brendon Cheung
  • 995
  • 9
  • 29
  • Closely related: https://stackoverflow.com/questions/16586809/why-is-it-allowed-to-access-a-private-field-of-another-object – T.J. Crowder Sep 17 '19 at 14:47
  • I struggle to imagine what you think "private" means. – Dave Costa Sep 17 '19 at 14:47
  • Alternative dupe: [Why can a “private” method be accessed from a different instance?](https://stackoverflow.com/questions/21900632/why-can-a-private-method-be-accessed-from-a-different-instance) – Ivar Sep 17 '19 at 14:47
  • Possible duplicate of https://stackoverflow.com/questions/792361/do-objects-encapsulate-data-so-that-not-even-other-instances-of-the-same-class-c. – T.J. Crowder Sep 17 '19 at 14:48
  • Thank you GBlodgett and khelwood. I **knew** there was one, I just couldn't find it. – T.J. Crowder Sep 17 '19 at 14:50

2 Answers2

2

private means that the method is inaccessible outside the class.

Since your main method is inside the Driver class, then the private methods of Driver are accessible.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
  • it would make sense if `printColor("blue");` was called without creating an object. does compiler simply ignore the `Driver` object and treat that line as if no object was created? – mangusta Sep 17 '19 at 14:47
  • In this case `printColor()` (which is a non-static method) is called from a `static` context, which is not allowed. – Konstantin Yovkov Sep 17 '19 at 14:49
  • I know that, that's what I mean - if `printColor` is called from inside the class it is defined, then probably compiler implicitly treats it as a static method – mangusta Sep 17 '19 at 14:53
  • No, it implicitly treats it as an _instance_ method (it would be the same if `this.printColor()` is called). – Konstantin Yovkov Sep 17 '19 at 14:54
1

I think you missunderstood what private means. It simply means: "You can't access this method from outside the Driver-class." And since you are inside the class, the compiler allows the access.

Christian
  • 22,585
  • 9
  • 80
  • 106