Reputation: 9579
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!
}
}
Upvotes: 2
Views: 4510
Reputation: 463
You could access non static methods from static method by having instance of the class which containing non-static method. so here
you can call non static method as you have an instance
you can call private method as both methods in the same class.
Upvotes: 1
Reputation: 79838
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.
Upvotes: 1
Reputation: 68715
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.
Upvotes: 2
Reputation: 4746
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
}
}
Upvotes: 0
Reputation: 691755
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.
Upvotes: 7