Witscale Test Center

11.1 Encapsulation and implementation hiding > 11.1.1 Implementing tight encapsulation


11.1.1 Implementing tight encapsulation

Tight encapsulation means you should hide every implementation details (all member variables and methods which the user of your code need-not-know). It also suggests that only the services provided by your class should be declared as public methods. You should take following steps to tightly encapsulate any Java class.

 

1.       Restrict access to all member variables ( usually with private access modifier)

2.       Provide public accessor methods for member variables. Thus the users of your class are compelled to access the member variables only through the accessor methods you specified.

3.       Expose the service methods of the class by declaring them as public.

 

For instance, a tightly encapsulated Elephant class will have all its member variables as private with public getter and setter methods. It will also have all internal methods (the methods that need not be used by the users, for example mudBath()) as private. Any service method which Elephant can provide, for example timberLogging(), should be made public. Now that we know how to encapsulate, let us summarize why to encapsulate briefly.

 

Exam questions based on encapsulation may ask whether you can predict surely the value of some public variable (say age) of a class (Elephant) if no method is called. Be careful with such questions, as it is possible to change a public variable without calling any methods. The public variable can be referred and changed directly on the class instance (bigElf.age).