Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Encapsulation Concept not clear

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.

like image 925
user2693404 Avatar asked Sep 27 '13 06:09

user2693404


People also ask

What are the disadvantages of encapsulation?

Disadvantages of EncapsulationCode Size:The length of the code increases drastically in the case of encapsulation as we need to provide all the methods with the specifiers. More Instructions: As the size of the code increases, therefore, you need to provide additional instructions for every method.

What are the rules of encapsulation in Java?

In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding. Declare the variables of a class as private. Provide public setter and getter methods to modify and view the variables values.

How can the concept of encapsulation can be achieved in a program?

Encapsulation can be achieved by Declaring all the variables in the class as private and writing public methods in the class to set and get the values of variables. It is more defined with the setter and getter method.

How encapsulation is achieved in Java explain with example?

Example 1: Java EncapsulationTo calculate an area, we need two variables: length and breadth and a method: getArea() . Hence, we bundled these fields and methods inside a single class. Here, the fields and methods can be accessed from other classes as well. Hence, this is not data hiding.


3 Answers

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

  • Encapsulation
  • Accessors

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

like image 170
user2339071 Avatar answered Sep 28 '22 08:09

user2339071


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

}
like image 29
Juned Ahsan Avatar answered Sep 28 '22 09:09

Juned Ahsan


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

like image 33
Subhrajyoti Majumder Avatar answered Sep 28 '22 09:09

Subhrajyoti Majumder