In the introduction of this tutorial I mentioned that one of the reasons Object-Oriented programming is so useful is that you can create objects that hide a lot of the variables and functionality associated with a programmatic solution. Deciding what level of visibility you allow into an object is an important consideration. In Java there are three levels of data hiding or “encapsulation“:
|A public field or method can be accessed by any other method in any other object or class.
|A protected field or method can be accessed by any method in the class in which it is declared or by any method defined in subclasses of that class.
|A private field or method can only be accessed by methods in the class in which it is declared, but not in the subclasses.
Generally, you should always try and make your fields private. This ensures their values can only be altered via methods you create. Methods will require greater visibility than fields since they are how a user interacts with the object.
So with this knowledge, be sure to keep an eye on the different encapsulation being used throughout this project. Also note that we now have UML terminology we can incorporate into diagrams, I’ll use these in subsequent ones.
The “Final” keyword
The last thing I’ll explain in this section is the keyword “final“. This basically means that when this variable or constant gets a value, that is it’s value for the remainder of the object’s life. This can be really handy if the value of a field needs to only be set once, so again keep an eye out for how and when I use this!