25

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.

jxh
  • 69,070
  • 8
  • 110
  • 193
user2693404
  • 307
  • 1
  • 3
  • 9

12 Answers12

40

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. :)

Community
  • 1
  • 1
user2339071
  • 4,254
  • 1
  • 27
  • 46
  • 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? – user2693404 Sep 27 '13 at 10:12
  • The explanation is already given by @Zeeshan. His explanation is a very clean one. :) – user2339071 Sep 27 '13 at 11:40
6

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);
    }

}
Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
  • 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. – user2693404 Sep 27 '13 at 07:13
  • @JunedAhsan can you please tell what is `Employee.main(null);` doing in your code above? – Amit Upadhyay Jul 28 '17 at 10:24
4

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

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
  • 2
    How does `static` break encapsulation? The declaration of the member variables as `public` violates encapsulation, but why would `static` violate it in general? – Viktor Seifert Sep 27 '13 at 07:25
  • 1
    `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;`. – Josef May 03 '15 at 14:59
2

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");
                }
}
Rohit Gaikwad
  • 3,677
  • 3
  • 17
  • 40
  • 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? – hardik9850 May 27 '18 at 11:06
1

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.

Community
  • 1
  • 1
Zeeshan
  • 2,884
  • 3
  • 28
  • 47
  • 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. – user2693404 Sep 27 '13 at 09:48
  • @user2693404 i have edited the answer with example. did it help now? did you understand the concept? any questions? – Zeeshan Sep 27 '13 at 10:25
  • 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. – user2693404 Sep 27 '13 at 11:04
  • @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? – Zeeshan Sep 27 '13 at 13:41
1

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.

Lefteris Laskaridis
  • 2,292
  • 2
  • 24
  • 38
1
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;
}
Satheesh Guduri
  • 353
  • 4
  • 8
1

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.

n ramesh
  • 11
  • 1
0

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.

William Gaul
  • 3,181
  • 2
  • 15
  • 21
0

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.

Abderrahmen
  • 440
  • 3
  • 6
0

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.

smriti
  • 1
  • 2
0

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.

Purvi Modi
  • 1
  • 1
  • 2