Encapsulation Vs Plain

前端 未结 4 1773
你的背包
你的背包 2021-01-19 22:05

Why should I use encapsulation if the code below will produce the same result?

The main benefit of encapsulation is the ability to mo

相关标签:
4条回答
  • 2021-01-19 22:36
    1. By providing getters and setters we get the benefits of hiding the implementation. e.g. You can use lazy initialization, proxies etc.
    2. Code becomes more maintainable e.g. you can easily add pre and post checks (or validations) at one place. If you access the variable directly and later on you need to add any validation or some default behaviour while reading the value you would have to change it at multiple places.
    3. By getters and setters you get the benefits of polymorphism. e.g. if you don't want value of the variable to be changed in extended version or vice versa, you can simply throw exception.

    From debugging point of view:

    1. Provides the segregation of code lines where the variable's value is accessed or updated. (Can be used to check references)
    2. Sometimes, we need to know where the value of variable got changed. You can put debug pointer or logger to investigate it.
    0 讨论(0)
  • 2021-01-19 22:45

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

    public class Person {
    
    private String name;
    private Date dob;
    private transient Integer age;
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public Date getDob() {
        return dob;
    }
    
    public void setDob(Date dob) {
        this.dob = dob;
    }
    
    public int getAge() {
        if (age == null) {
            Calendar dob_cal = Calendar.getInstance();
            dob_cal.setTime(dob);
            Calendar today = Calendar.getInstance();
            age = today.get(Calendar.YEAR) - dob_cal.get(Calendar.YEAR);
            if (today.get(Calendar.MONTH) < dob_cal.get(Calendar.MONTH)) {
                age--;
            } else if (today.get(Calendar.MONTH) == dob_cal.get(Calendar.MONTH)
                    && today.get(Calendar.DAY_OF_MONTH) < dob_cal.get(Calendar.DAY_OF_MONTH)) {
                age--;
            }
        }
        return age;
      }
    }
    

    Method getAge() returns you the persons age and you need not bother about how it is implemented and you need not calculate age outside the class.

    0 讨论(0)
  • 2021-01-19 22:45

    One way to use encapsulation is to hide implementation. Sometimes a getter, for example, isn't a getter. Consider a shape like a sphere, I wouldn't necessarily store the volume or surface area as a variable because I could calculate them at any time. I would still call the member functions getVolume and getSurfaceArea. The person who uses my code doesn't need to know if I calculate or simply store the value. By exposing my variables I lock them into a design decision that would have to change (or be broken) should I change my implementation. By hiding implementation you need only know the interface (not to be confused with Java's 'interface' ) It protects everybody that way and makes making future changes a much easier task.

    It should be noted that there are times when setters/getter are not used and variables are exposed. Even in Java sometimes it just makes more sense not to hide instance variables.

    0 讨论(0)
  • 2021-01-19 22:46

    Your question is quite interesting. I will try to answer it to you in-depth.

    The main idea behind encapsulation is to hide the data and its implementation details from other users. If we make a data member private then it can only be accessed within the same class. No other class can ever access that piece of data directly.

    But we can define an interface, i.e. public getter and setter methods to update the data from other classes. This ensures that the private data remains inaccessible to others and can only be accessed by the public methods you provide.

    For instance, you may decide to provide only the getter method for a particular data member and no setter method. This ensures that no other class can change or update your data member in any possible way. They can only get the value if they want using the getter method.

    This is why encapsulation is also known as Data Hiding.

    Example

    public class EncapsulationDemo{
        private int ssn;
        private String empName;
        private int empAge;
    
        //Getter and Setter methods
        public int getEmpSSN(){
            return ssn;
        }
    
        public String getEmpName(){
            return empName;
        }
    
        public int getEmpAge(){
            return empAge;
        }
    
        public void setEmpAge(int newValue){
            empAge = newValue;
        }
    
        public void setEmpName(String newValue){
            empName = newValue;
        }
    
        public void setEmpSSN(int newValue){
            ssn = newValue;
        }
    }
    public class EncapsTest{
        public static void main(String args[]){
             EncapsulationDemo obj = new EncapsulationDemo();
             obj.setEmpName("Mario");
             obj.setEmpAge(32);
             obj.setEmpSSN(112233);
             System.out.println("Employee Name: " + obj.getEmpName());
             System.out.println("Employee SSN: " + obj.getEmpSSN());
             System.out.println("Employee Age: " + obj.getEmpAge());
        } 
    }
    

    Advantages

    1) It provides flexibility to the code and makes it easily maintainable. We can change the implementation of getEmpName() or setEmpName() without affecting any other outside code.

    2) We can make data members read-only (by only defining getters) or write-only (by only defining setters) anytime.

    3) Other users will not be knowing what is going on behind-the-scenes. They will only know that to update a data, we need to call the settter methods and to get a data we need to call the getter emthods.

    0 讨论(0)
提交回复
热议问题