I don't understand why I can access the private int i
outside of the class while it's private.
public class Fish {
private int i = 1;
public static void main(String[] args) {
Fish k = new F开发者_运维问答ish();
k.i = 2; // it IS possible
}
}
Access modifiers work on class level not on object level.
You are allowed to access k.i
since the code lies within the same class as in which the member i
is declared.
The rationale is (afaik) the following: You encapsulate the data (partly) in order to ease future maintenance and refactorings. When you refactor code, you refactor classes, not objects.
Your main method is part of the Fish class isn't it?
The following doesn't work:
public class Fish {
private int i = 1;
}
class Reptile{
public static void main(String[] args) {
Fish k = new Fish();
k.i = 2; // Compiler error.
}
}
Private means that only the defining class can access the variable.
Your main method is a method of the class Fish, and so it is allowed to access the variable
This is not outside the class. You're in the same class.
You're instantiating a new instance of the same class and therefore you can access the private fields of this class.
If this were the main method in SomeOtherClass, the same line would fail.
精彩评论