正文
Encapsulation
Exposed means reachable with the dot operator, as in:
theCat.height = 27;
Think about this iead of using our remote control to make a direct change to the Cat object's size instance variable.
就是说如果不控制好猫的身高,随意让别人改动的话,猫的身高有可能变成0,这不是我们想要的,所以要保护好。
Hide the data
Yes it is that simple to go from an implementation that's just begging for bad data to one that protects your data and protects your right to modify your implementation later.
OK, so how exactly do you hide the data? with the public and private access modifiers. You are familiar with public- we use it with every main method.
Here's an encapsulation starter rule of thumb (all standarad disclaimers about rules of thumb are in effect): mark your instance variables private and provide public getters and setters for access control.
Instance
variables are declared inside a class but not within a method. It is what the object
knows
. 说白了instance就是对象知道的数据,比如猫知道自己的身高,体重等等。
Local
variables are declared within a method. 就是说local variables只是在执行任务时候用的,比如算两个数的总和,那用x和y就可以了,不用身高和体重。
Local
variables MUST be initialized before use! Local variables do NOT get a default value! THe compiler complains if you try to use a local variable before the variable is initialized.
x++ 和++x不是一回事
THe placement of the operator(either before or after the variable) can affect the result. Putting the operator before the variable (for example, ++x), means, "first, increment x by 1, and then use this new value of x." This only matters when the ++x is part of some larger expression rather than just in a single statement.
int x = 0; int z = ++x;
produces: x is 1, z is 1
But putting the ++after the x give you a different result:
int x = 0; int z = x++;
produces: x is 1, but z is 0! z gets the value of x and then x is incremented.