Thursday, March 12, 2009

What is Tight Encapsulation? (CoreJava)

Question :What is Tight Encapsulation? (CoreJava)
Answer :Encapsulation is for member variables in a classes that may not be
accessed by any other classes. Below are few examples
Example 1:
class Test {
private String name;
This class is tightly encapsulated as you can't access the member "name".
Example 2:
class Test2 {
private String name;
public void setName(String name) {
if(name.equals("test2") { = name;
else {
//throw user exception
public String getName() {
return name;
The standard way to protect the data is to make it private, so that no other
class can get direct access to it, and
then write public methods to get the data and set the data. The method
that sets the data should carry out appropriate
checks to make sure the incoming data is valid.
In Example 2 we are validating the incoming data with "test2". If its test2
we are allowing the data to be set, else
we are throwing an exception.
Tight encapsulation will not only protect direct access to data members,
but will also prevent those members from being
set to improper values.

No comments: