Search code examples
javastaticprivateencapsulation

Why static methods are allowed to invoke private methods?


I have never tried to write the following code before, because it does not make much sense in production. But surprisingly to me this code compiles successfully. Why it was designed to allow calling private methods from static methods on instances of the same class?

public class Beverage {
    private void drink () {
        System.out.println("Beverage");
    }

    public static void main (String[] args) {    
        Beverage b = new Beverage();
        b.drink(); //call to private method!
    }
}

Solution

  • Why wouldn't they be able to call them? private restricts access to the same class. The static method is in the same class. So it has access to the private method.

    Access modifiers work at the class level, not at the instance level. It they worked at the instance level, you couldn't write static factory methods (calling private constructors and initialization methods), equals() methods and compareTo methods (comparing private fields of two instances), etc.