By user2693404


2013-09-27 06:47:35 8 Comments

This is basic question but still i don't understand encapsulation concept . I did't understand how can we change the properties of class from other class.because whenever we try to set the public instance value of class we have to create object of that class and then set the value.and every object refer to different memory.so even if we change the instance value this will not impact to any other object.

Even I try to change using static public instance value also i am not able to change the class property value.

Example is given below

// Employee class
public class Employee {
    public static int empid;
    public static String empname;

    public static void main(String[] args) {
        System.out.println("print employe details:"+empid+" "+empname);
    }

    // EmployeeTest  class
    public class EmployeeTest {

        public static void main(String[] args) {
            Employee e = new Employee();
            e.empid=20;
            e.empname="jerry";
            Employee.empid=10;
            Employee.empname="tom";
        }

    }
}

Every time I run Employee class I am getting same value

print employe details:0 null

Even though I am not following encapsulation concept and I am not able to change public instance value of employee class.Please help me to understand the concept where i am going wrong.

12 comments

@Zeeshan 2013-09-27 06:59:55

of course, change on one object will not impact on another object. suppose you have a class student and all the children at your school are it's objects. if one leaves the school, this doesn't mean, every other student (object of student class) should leave the school too.

Encapsulation is the concept of having your class variables as private, so that no one can directly play with your data members from outer world. but you provide the public method, to let the outer world play with your data member, the way you want them to. the nice coding example of encapsulation is given above by Subhrajyoti Majumder.

(static members are same for all objects of the class. eg: static count variable, to count the number of student class objects. (number of students at school)).

Edit as you asked for:

Example:

public class student{
    public String name;
    public student() {}
 }

and in your main function, outer world can play with your class attributes as:

student s = new student();
s.name = "xyz";

let's suppose, you don't want to let the outer world change your name attribute of object. then you should make name 'name' as private, and provide a public method to only view the name (get).

Example:

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

and now in your main method, you can only get the name object, and can't set it to new value, like you could do in first example.

student s = new student();
String sname = s.getName();

and if you try:

s.name = "newname";

compiler will not allow you that. since you don't have permission to access the private members.

@user2693404 2013-09-27 09:48:14

Thanks guys can you please give exmaple class with encapsulation and without encapsulation and how results will be different in both the case.I mean I want to see difference in o/p in both the implementation.

@Zeeshan 2013-09-27 10:25:30

@user2693404 i have edited the answer with example. did it help now? did you understand the concept? any questions?

@user2693404 2013-09-27 11:04:11

student s = new student(); s.name = "xyz"; This change is for only only object 's' right,change is not at class level it will not impact any other object right.so how encapsulation is useful for us?This s.name = "xyz"; will impact only object s not impact any other object.

@Zeeshan 2013-09-27 13:41:16

@user2693404 please read the second paragraph of my answer. Encapsulation is not about if it will effect the only 's' object or the every created object. Encapsulation is a technique, which is mentioned in second paragraph of my answer, and its example is given at end. and as far as effect of change is concerned, i have also mentioned in the end that only static type of variable will be same for every created object of student class. imagine the case, where you want to count number of student objects created. any other question?

@Purvi Modi 2017-06-13 09:36:52

Do you mean to say that the value of empid should be 10 and empname tom instead of 0 and null, if yes then-:

1)memory to the variables is allocated at run time , and also deallocated after the program is terminated.

2)Hence if you think that once if you give 10 to empid it should always be 10, it is not so , because empid is just a reference to a memory which is storing "10".

3)So by deallocation , i mean that empid is no longer pointing to memory area storing 10, after the program terminates

4)whenever you execute a new program , the empid is now pointing to other memory area , and that memory is allocated the the default value according t the respective datatype,in case of static variable. hence always 0 and null.

@smriti 2017-04-18 19:10:40

ENCAPSULATION is mechanism of wrapping methods and variables together as a single unit. for example capsule i.e. mixed of several medicines.

variables of a class will be hidden from other classes as it will be declared private, and can be accessed only through the methods of their current class

To achieve encapsulation in Java − * Declare the variables of a class as private. * Provide public setter and getter methods to modify and view the variables values. * The Java Bean class is the example of fully encapsulated class.

@Rohit Gaikwad 2016-09-12 12:53:23

Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class. Access to the data and code is tightly controlled by an interface.

Encapsulation in Java is the technique of making the fields in a class private and providing access to the fields via public methods.

If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.

Real-time example: cars and owners. All the functions of cars are encapsulated with the owners. Hence, No one else can access it..

The below is the code for this example.

public class Main {

  public static void main(String[] args) {
    Owner o1=new Car("SONY","Google Maps");
    o1.activate_Sunroof();
    o1.getNavigationSystem();
    o1.getRadioSytem();
 }
}  
//Interface designed for exposing car functionalities that an owner can use.
public interface Owner {
     void getNavigationSystem();
     void getRadioSytem();
     void activate_Sunroof();
}
/*
Car class protects the code and data access from outside world access by implementing Owner interface(i.e, exposing Cars functionalities) and restricting data access via private access modifier.
*/
public class Car implements Owner {
                private String radioSystem;
                private String gps;

                public Car(String radioSystem, String gps) {
                    super();
                    this.radioSystem = radioSystem;
                    this.gps = gps;
                }

                public String getRadioSystem() {
                    return radioSystem;
                }

                public void setRadioSystem(String radioSystem) {
                    this.radioSystem = radioSystem;
                }

                public String getGps() {
                    return gps;
                }

                public void setGps(String gps) {
                    this.gps = gps;
                }

                @Override
                public void getNavigationSystem() {
                    System.out.println("GPS system " + getGps() + " is in use...");
                }

                @Override
                public void getRadioSytem() {
                    System.out.println("Radio system " + getRadioSystem() + " activated");
                }

                @Override
                public void activate_Sunroof() {
                    System.out.println("Sunroof activated");
                }
}

@Hardik9850 2018-05-27 11:06:56

by providing public setters aren't you exposing entity detail to outside world? eventually defeating the whole purpose of encapsulation? How can we make it tightly controlled?

@Abderrahmen 2016-08-22 13:15:06

The encapsulation is an OOP concept. The class is considered like a capsule that contains data + behavior. The data should be private and should be accessed only using public methods called getters and setters. You may check this encapsulation tutorial for more informations about this concept.

@n ramesh 2014-11-20 11:25:07

encapsulation =VARIABLES(let private a,b,c)+ METHODS(setA&getA,setB&getB....) we can encapsulate by using the private modifier. let consider your created one public variable and one private variable in your class... in case if you have to give those variables to another class for read-only(only they can see and use not able to modify) there is no possibility with public variables or methods,but we can able to do that in private by providing get method. so Your class private variables or methods are under your control. but IN public there is no chance....i think you can understood.

@Satheesh Guduri 2014-05-28 14:28:09

Encapsulation means combining data and code together(class). The main purpose of encapsulation is you would have full control on data by using the code.

class Encap{

private int amount;

public void setAmount(int amount)
{
this.amount = amount;
}

Here, you can set the amount using the setAmount method, but value should be more than 100. So, i have the control on it.

public void setAmount(int amount)
{
if(amount>100)
this.amount = amount;
}

@Juned Ahsan 2013-09-27 06:52:39

It seems you are running two different classes separately and assuming the changes done to attributes when you run EmployeeTest will reflect in Employee run. Note that changes will reflect in the same JRE instance. Excuse me in case i have misunderstood your problem.

EDIT: As per the user input. Here is the code how you can access and update the static member values:

class Employee {
    public static int empid;
    public static String empname;

    public static void main(String[] args) {
        System.out.println("print employe details:" + empid + " " + empname);
    }
}

// EmployeeTest class
public class EmployeeTest {

    public static void main(String[] args) {
        Employee e = new Employee();
        e.empid = 20;
        e.empname = "jerry";
        Employee.empid = 10;
        Employee.empname = "tom";
        Employee.main(null);
    }

}

@TheLostMind 2013-09-27 07:01:09

+1 .. You are right.. He is running 2 instances...

@user2693404 2013-09-27 07:13:21

thanks for reply.can you please give an example where if we don't implement encapsulation concept how instance value can be changed.In my above example Employee class how we can change the instance value .if we don't implement encapsulation how it affect employee class in both case it work same whether we implement encapsulation or we don't implement encapsulation.

@Juned Ahsan 2013-09-27 11:14:35

@user2693404 check the edit part of my answer.

@Amit Upadhyay 2017-07-28 10:24:44

@JunedAhsan can you please tell what is Employee.main(null); doing in your code above?

@Subhrajyoti Majumder 2013-09-27 06:50:27

public static field's are associated with class not with object, it break Object's encapsulation rule.

Employee class with two encapsulated field empid & empname.

public class Employee {
    private int empid;
    private String empname;

    public int getEmpid(){
        return this.empid;
    } 
    public void setEmpid(int empid){
        this.empid = empid;
    }
    ...
}

public class EmployeeTest {
      public static void main(String[] args) {
            Employee e = new Employee();
            e.setempId(1);
            Employee e1 = new Employee();
            e1.setempId(2);
      }
}

Documentation for better understanding on encapsulation

@Viktor Seifert 2013-09-27 07:25:00

How does static break encapsulation? The declaration of the member variables as public violates encapsulation, but why would static violate it in general?

@Subhrajyoti Majumder 2013-09-27 07:25:46

ummm public static... right

@Josef 2015-05-03 14:59:59

static breaks encapsulation rule because it is possible to access it without settters or getters but directly. If you declare a variable like this : public static or static, when calling it from another class you can write : object.variable = value;.

@Lefteris Laskaridis 2013-09-27 07:12:20

The concept of encapsulation is a design technique that relates with information hiding. The underlying principle is to provide protected access to the class attributes, through a well designed interface. The purpose of encapsulation is to enforce the invariants of the class.

To follow on your example consider the interface of this class:

class Employee

  private final String firstName;
  private final String lastName;    

  public Employee(final firstName, final lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  public String getName() {
    return firstName + " " + lastName;
  }
}

Note that by declaring the attributes as private this class restricts clients from directly accessing the state of employee object instances. The only way for clients to access them is via the getName() method. This means that those attributes are encapsulated by the class. Also note that by declaring the attributes as final and initializing them in the constructor we create an effectively immutable class, that is one whose state cannot be modified after construction.

An alternative implementation would be the following:

class Employee

  private String firstName;
  private String lastName;    

  public Employee(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  public String getName() {
    return firstName + " " + lastName;
  }

  public String setName(String firstName, String lastName) {

    if (firstName == null) {
      throw new IllegalArgumentException("First name cannot be null");
    }

    if (lastName == null) {
      throw new IllegalArgumentException("Last name cannot be null");
    }

    this.firstName = firstName;
    this.lastName = lastName;
  }
}

In this example the object is not immutable but its state is encapsulated since access to it takes place only through accessors and modifiers. Note here how encapsulation can help you protect the invariants of the object state. By constraining modifications through a method you gain a better control of how the object state is modified, adding validations to make sure that any modifications are consistent with the specification of the class.

@user2339071 2013-09-27 07:07:27

Yeah, this can be a little confusing sometimes. Let's go step by step: First, you need to understand

  • What is encapsulation and why is it used.?

Encapsulation is one of the four fundamental OOP concepts.Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.

Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class. Access to the data and code is tightly controlled by an interface.

The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this feature Encapsulation gives maintainability, flexibility and extensibility to our code.

Take a small example:

public class EncapTest{

   private String name;
   private String idNum;
   private int age;

   public int getAge(){
      return age;
   }

   public String getName(){
      return name;
   }

   public String getIdNum(){
      return idNum;
   }

   public void setAge( int newAge){
      age = newAge;
   }

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

   public void setIdNum( String newId){
      idNum = newId;
   }
}

The above methods are called Accessors(aka getters and setters). Now you might ask,

  • Why should you use accessors..? There are actually many good reasons to consider using accessors rather than directly exposing fields of a class.Getter and Setters make APIs more stable.

For instance, consider a field public in a class which is accessed by other classes. Now later on, you want to add any extra logic while getting and setting the variable. This will impact the existing client that uses the API. So any changes to this public field will require change to each class that refers it. On the contrary, with accessor methods, one can easily add some logic like cache some data, lazily initialize it later. Moreover, one can fire a property changed event if the new value is different from the previous value. All this will be seamless to the class that gets value using accessor method.

There are so many tutorials and explanations as to how and what are they. Google them.

As for your, current problem:

  1. You have two different classes, each with a main. That is wrong. They will have different properties.
  2. Code change suggested by @Subhrajyoti Majumder is the correct one. Check the answer for solving the problem.

In the meantime, read up on

for a better understanding of the concepts. Hope it helps. :)

@user2693404 2013-09-27 10:12:16

Thanks for your reply it was very helpful , can you please can give me example where encapsulation is not implemented and how it can impact?

@user2339071 2013-09-27 11:40:38

The explanation is already given by @Zeeshan. His explanation is a very clean one. :)

@William Gaul 2013-09-27 06:54:40

The reason you are getting the output "print employe details:0 null" when running the Employee class is because those variables are not initialized. That is, you do not assign any values to them within the Employee class.

Whatever you do within the EmployeeTest class will not affect the values of the variables in Employee the next time it is run. Consider each run of a Java program a "clean slate".

On the point of encapsulation, you really should not be using the static keyword. If you are going for encapsulation check out the other answer to this question, it has a nice code sample for you to use.

Related Questions

Sponsored Content

86 Answered Questions

[SOLVED] Is Java "pass-by-reference" or "pass-by-value"?

47 Answered Questions

[SOLVED] Does a finally block always get executed in Java?

41 Answered Questions

[SOLVED] How do I efficiently iterate over each entry in a Java Map?

27 Answered Questions

43 Answered Questions

[SOLVED] How do I convert a String to an int in Java?

28 Answered Questions

[SOLVED] How do I determine whether an array contains a particular value in Java?

  • 2009-07-15 00:03:21
  • Mike Sickler
  • 1886036 View
  • 2185 Score
  • 28 Answer
  • Tags:   java arrays

32 Answered Questions

[SOLVED] When to use LinkedList over ArrayList in Java?

65 Answered Questions

[SOLVED] How do I generate random integers within a specific range in Java?

  • 2008-12-12 18:20:57
  • user42155
  • 3905444 View
  • 3361 Score
  • 65 Answer
  • Tags:   java random integer

55 Answered Questions

[SOLVED] Creating a memory leak with Java

57 Answered Questions

[SOLVED] How do I read / convert an InputStream into a String in Java?

Sponsored Content