Getters and Setters.
These set the values for Instance variables and get the value of them when you ask for it. They are basically methods.
One of the pillars of Object oriented language. One design approach, Make all the Instance variables private. Then make the Getters and Setters as public. So, In case you want to access or modify the variables you do it through these methods.
One might ask, what is the need for this approach? Well you see some variables have boundary condition like values cannot be negative or lets say a weight cannot be below a certain threshold etc. The Methods are gonna enforce those boundaries.
One more cool thing would be that, if one wants to make any change to the code which is used by lot of people you wont be breaking anything.All you need to do change the methods.
if you try to use a variable directly that is not been initialized the compiler will give an error. Still these are the default values. However interestingly , if use the variables through a method you will get default values.
Another explanation for this is about Instance Variables and Local Variables.
Variables declared within a class are instance variables, the ones declared within a method are local variables. Local variables have to initialized before use, they do no get a default value.
Use == to check if two variables/primitives or references are equal
Use equals method to check if two objects are same
int a = 3;
byte b = 3;
if ( a == b ) // true
dog d1 = new dog();
dog d2 = new dog();
dog d3 = d2;
if( d1 == d2 ) // false
if( d3 == d2) // true
Missed to note the return type
requires lot of tracing.
Here is the puzzle , i am adding the solution directly below. This i found quite tricky , so try it out first before checking the solution.
Green stuff is called tracing. Tracing is a process where you follow the states of each variables in the program and see how they change with each iteration. I found that unless i did tracing i could not come up with the return values.
I found it very satisfying to do it myself. Very important aspect applicable to any problem solving. If you cant solve a problem in one attempt. Leave it. Dont spend too much time, because once you get into a certain mode of thinking and that doesn not help then that mode is not good enough to solve that problem. This is deeply psychological. You need to give it some time. Check it after few hours or check it after a day. You will be surprised to know, how differently you can attack the same problem and solve it with relative ease.
There is very interesting video on YouTube by Barbara Oakley on How to Learn. Check it out, She tries to explain various modes of thinking essential in learning.
next page 117
More in next part.
Head First Java 2nd Edition