user724747
user724747

Reputation: 107

Clarity on encapsulation in java

I went through few blogs from which i got below points. Encapsulation Blog

  1. Do not expose the fields as public, as any other class can modify the variables directly.
  2. Use getter's and setter's to modify the variables.
  3. By including validations in the getter and setter's, we can control the variables will not be directly modified.

I'm little confused here.

Consider Employee which has name and address as its fields. Organization and Organization2 classes will assign values to employee variables and print the same.

public class Employee {

    public String name;
    public String address;

    public void printEmpDetails() {
        System.out.println("Employee name :" + name + ", Employee address :"
                + address);
    }
}

public class Organization {

    public static void main(String[] args) {
         System.out.println("Employee details of org");

         Employee emp = new Employee();  //New Instance variable created
         emp.name= "JOHN";
         emp.address = "JOHN ADDRESS";     

    }
}

public class Organization2 {

    public static void main(String[] args) {
         System.out.println("Employee details of org2");

         Employee emp = new Employee();  //New Instance variable created
         emp.name= "JAMES";
         emp.address = "JAMES ADDRESS";     

    }
}
  1. Organization is creating an employee instance (which assigns it's own set of values to employee)
  2. Similarly Organization2 is also creating an employee instance (which assigns it's own set of values to employee)

Question: Since it is two different instances. How is encapsulation violated here?

Upvotes: 2

Views: 668

Answers (5)

Mureinik
Mureinik

Reputation: 311103

The point of encapsulation is not to prevent different instances from effecting each other, it's about keeping a clear distinction on which class owns the data and where the logic related to it should lie.

Assume, for example, that you want to introduce an additional property to Employee which contains the number of times he was renamed. If you expose the data members as public, each organization class that uses Employee needs to remember to update this new property.

However, if your data members are private, and other class can only manipulate them with the class' methods, you can assure to encapsulate this logic within the class:

public class Employee {

    private String name;
    private int numRenames = 0;

    public String getName() {
        return name;
    }

    public in getNumRenames() {
        return numRenames;
    }

    public void setName(String name) {
        this.name = name;
        ++numRenames;
    }

    // rest of the class snipped
}

Upvotes: 0

user784540
user784540

Reputation:

The main point is to do not expose class internals to outside. This rule needs to provide flexibility to your code.

In your code, into Organization and Organization2 classes, you access Employee class fields directly. Instead of that, it is recommended to declare setters and getters for both variables.

public class Employee {

   private String name;
   private String address;

   public String getName() {
     return this.name;
   }

   public String getAddress() {
     return this.address;
   }

   public void setName(String newName) {
     this.name = newName;
   }

   public void setAddress(String newAddress) {
    this.address = newAddress;
   }

}

Note, that fields name and address are declared as private.

For example, if you have redesigned the internal structure of Employee class, you will need to rewrite only getters and setters. All the rest of your code will not require the intervention.

In case you access name and address fields directly, you will need to rewrite all code, where you access these variables, in case you change these variable names, or even use another data source, instead of these variables.


Update №1

In your case encapsulation means that you need to hide the implementation of Employee class inside of this class. Exposing variable names exposes internal structure of your class and all code which interacts with your Employee class is rigidly bounded to your Employee class structure.

Assume the following situation. Your customer now asks you to modify inner structure of your Employee class. You should store only customer id (a new class field), but name and address should be read from a database.

In case you have getters and setters you will need to rewrite only these getters and setters of Employee class. Your external code will not notice this change.

But in case you access name and address directly, you will need to change code in Organization and Organization2 classes.

Now imagine you have 300 classes, which are accessing to each other directly.


Update №2

Your question in the chat, when I was away:

Thanks Here is my undestanding on the abstraction and encapsulation. Taking the car example itself Abstraction - Hide the internal working of a feature in a car. Say Break system - Car Manufacturer's tell that - If you press break, It will stop (Here we are hiding how break system works) Encapsulation - Provide a public interface to access the breaks. Car users should use that particular public interface to operate the breaks. As a manufacturer i can decide on what logic to be implemented when a user applies break and this logic can change in future without the user's notice.

My answer:

yes, a manufacturer provides only public interface (the break pedal), and a driver should not worry about the internal mechanism of the system. If a manufacturer decides to change the mechanism, he needs to preserve public interface (the break pedal), and can change internals of the mechanism. And driver will not notice that change. The same approach works for programming classes. If you hide (encapsulate) internals of your classes, you make your application more maintainable and flexible.

Upvotes: 1

dark knight
dark knight

Reputation: 85

The basic concept of encapsulation is to hide the implementation. While you can do the same work making the fields public , you are giving direct access to the implementation of that class. that's why it is said to use getter,setter method.

But it all depends upon what you are trying to do . Sometimes it may be better to provide direct access without implementing any getter, setter method

Upvotes: 0

pathfinderelite
pathfinderelite

Reputation: 3137

This sounds like homework. However, I'm in a good mood, so I'll still help you :)

Do not expose the fields as public, as any other class can modify the variables directly.

public class Employee {

public String name;
public String address;

The fields are public, so it breaks encapsulation.

Upvotes: -1

shruti1810
shruti1810

Reputation: 4037

Encapsulation is violated for Employee class. The variables name and address are public. They should be made private and getters and setters should be defined for them.

Upvotes: 2

Related Questions