Question

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!
    }
}
Was it helpful?

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.

OTHER TIPS

Access level modifiers determine whether other classes can use a particular field or invoke a particular method. private access specifier limit the visibility from outside the class but it allows the method/field to be visible and usable inside the class.

You could access non static methods from static method by having instance of the class which containing non-static method. so here

  1. you can call non static method as you have an instance

  2. you can call private method as both methods in the same class.

static members are class members and non static members are instance members. Here you have used an instance to invoke an instance method which is totally fine. but you can't call as below.

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

    public static void main (String[] args) {    

        drink(); //call to private method!this is wrong no matter private or public
    }
}

The behaviour that you've noticed is the behaviour that is the most consistent with the definition of private.

In Java, private means "only able to be called from within the same class". It doesn't mean "only able to be called by the owning object". I suspect that this is a hold-over from Java's origins, where a lot of decisions were made for reasons of similarity with C++, which has the same definition of private.

It also allows you to do things like have a class with only private constructors, and static methods for instantiating the class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top