Encapsulation

Instance, or object, variables are declared immediately following the class declaration in a program. This makes the variables global, thus they can be referenced anywhere inside the class. It is important that class variable declarations pay attention to encapsulation.

Encapsulation is the idea that a class should manage/protect it's own information. We declare all variables in a class as private so that outside programs can't alter their values without being checked in a method. This is helpful for two reasons: Other visibility modifiers include public (all can see) and protected (sub classes can see). /** * Class ClassName * Represents a general class and all of its properties * @author M. Engel * @version 2005.9.11 */ public class ClassName { //list all variables here private int quantity; private double taxRate; private String id; //list all methods here }

Getters/Setters

In order to encapsulate and protect the private instance variables in our classes, we have made them private. This means that users of our classes do not have direct access to them (object.varName will not work). However, making variables private also means that we do not have access to see them (System.out.println(object.varName) will not work) or to alter their values after creation (object.varName=value; will not work).

For this reason, we need to create accessor (or getter) methods and mutator (or setter) methods in our classes. For each instance variable in a class, the designer decided if getter and setters are appropriate. In some cases, there may be variables whose values are determined by calculations and should not be set, or values that other methods need to access behind the scenes that users should not be able to access.

If we were writing a dog class to be used in a Veterinary Hospital, we may have the following setup: public class Dog { private String name; private int cage; }
When a Dog comes into the hospital and is entered into the system, its name is entered. While our users should be able to access the dog's name, they should not be able to change it. So the name variable will have a getter but not a setter. On the other hand, we will also assign the dog a cage. It may be that during the dog's stay, it needs to be moved to another cage. So, the cage variable will need both a setter and a getter. Also, remember that part of the reason for encapsulation is to verify the values of our instance variables. So, since the vet's office only has 20 cages, we will limit the incoming values in the setter to be between 1 and 20. public class Dog { private String name; private int cage; public String getName(){ return name; } public int getCage(){ return cage; } public void setCage(int c){ if(c>=1 && c<=20) cage=c; else cage=1; } }
*Note the use of the words 'set' and 'get' in the method names to make it clear what the purpose of the method is.