Search code examples
javaprivate

Why does this Java code compile and run? I do not understand it


I am studying for my certification exam, and I run into this example that compiles and runs, but the problem is that I do not think that it should compile, since the method is private and we are trying to invoke a private method from an instance of the class. Can someone please explain to me why it works?

Here is the code:

public class Test {
    public static void main(String[] args) {
        Test instance = new Test();
        System.out.println(instance.number());
    }

    /* protected */ private int number() {
        try {
            new RuntimeException();
        } finally {
            return 1;
        }
    }
}

Solution

  • The private methods and fields are accessible anywhere from the declaring class, even if called not from inside the instance method:

       class Test {
          private void doThis() {};
    
          public static void main() {  
             Test a = new Test();
             Test b = new Test();
    
             a.doThis(); // No problem
             b.doThis(); // No problem
          }
       }
    

    P.S. The method in your code was initially protected, not private (protected methods are accessible anywhere in the same package and also outside the package in derived classes). I have edited to make it private now. Also such code compiles and runs.