Reputation: 83
I am using Java
public class Drink {
private String contents;
Drink(String theContents){
contents = theContents;
}
public static void main(String[] args) {
Drink water = new Drink("water");
Drink oj = new Drink("orange juice");
Drink cocaCola = new Drink("Coca Cola");
oj.contents = "not orange juice";
System.out.println(oj.contents);
}
}
I thought the output should be an error.
e.g.the line oj.contents = "not orange juice";
should produce an error.
If this is wrong please tell me why :) thanks
Upvotes: 0
Views: 897
Reputation: 4644
From the official docs This picture will sum it up for you:
Any method or variable marked with the "private" access modifier is accessible to the class where it is defined. Any component outside of that class won't be able to access. Though you should also check about Reflection in java which an exception to this rule.
Upvotes: 0
Reputation: 506
Public variables, are variables that are visible to all classes. Private variables, are variables that are visible only to the class to which they belong. Protected variables, are variables that are visible only to the class to which they belong, and any subclasses.
variable content is not visible to other classes because it is private. But you can access it anywhere in the class Drink
Upvotes: 2
Reputation: 1287
You have only one class called Drink which contains the variable and the main method. Therefore the main method can access the private variable, because they are in the same class. If you would want to access the variable from another class, you would need getter and setter methods to do so.
Upvotes: 2
Reputation: 102822
private
mostly means: Visible to the same source file (and therefore editable; private/public/package-private/protected are all an all-or-nothing affair).
Here's a good (IMO) way to think about it: Code is a concept that goes with classes; not instances of those classes. Therefore, your code here is modifying one of its own fields: contents
is a private field of this very source file. "But, it's not your own, it is from drink oj
!" - nope, that's object-based thinking. class-based thinking says: It's the field "Drink.contents", which is in this file.
Upvotes: 0