Not surprisingly, private methods, variables, and classes are not accessible to (and hidden from) the public. Be aware, that the private instance variables, etc. still exist outside of the class. They are simply sheltered from the outside world. There is a big difference between being hidden and being absent.
As a design rule, you should almost never have instance variables declared public. They should not be accessible from the outside world. Why? Making them private is a way to hide information. When you use the SavitchIn methods, there is a lot of work going on behind the scenes, but you do not need to know about that because you are only concerned with what the class and methods are designed to do. That is, get a number or String for you.
Private methods and variables are not accessible (by name) outside of the class definition. Public methods and variables are accessible everywhere. Making variables private and methods public helps in information hiding. Section 4.2 from the book covers this topic and hopefully everyone has read it because it will be very important in writing well-documented code. To aide in this point, we shall convert the Stat class (located from previous lectures) to a more "proper" class with the variables made private and access granted through what are termed - accessor and mutator methods. Notice this class allows nearly full control over the instance variables, you have access to the strength, intelligence, and defense, but limited access to the hitPoints.
Accessor methods allow access to a private variables value from outside the class
and mutator methods allow private variables to be changed from outside.
For instance, here is a simple class to access one private variable.
public class JustAnInt {
private int num;
int getNum() { return num; } // Accessor method
void setNum(int newNum) { num = newNum; } // Mutator method
}
For example, in String name = "Christian", the variable name does not actually store the string "Christian". It stores a reference to memory where this string is actually stored. We shall look at a simple class in lecture which shows the difference between the two uses and some pitfalls associated with using them. See classes JustAnInt and JustAnIntDemo given in the handout.
Things to notice when using Class Types (rather than Primitive data types):
Things to notice when passing Class types versus primitive data types: