What is the use of encapsulation when I'm able to change the property values with setter methods?

前端 未结 15 2041
情深已故
情深已故 2020-12-08 11:08

I try to understand a lot of times but I failed to understand this.

Encapsulation is the technique of making the fields in a class private and provi

相关标签:
15条回答
  • 2020-12-08 11:39

    Any how i am able to change the values of fields through setter methods.

    Only if the setter method lets you do that.

    How we are preventing the accessing fields?

    The setter and getter get to control if and how you can access the fields.

    A setter may check if the value is valid. It may ask a SecurityManager if you should be allowed to do this. It may convert between data types. And so on.

    0 讨论(0)
  • 2020-12-08 11:39

    If you have private fields they can't be accessed outside the class, that means basically those fields don't exist to the outside world and yes you can change their value through setter methods but using setter methods you have more flexibility/control to say who gets to change the fields and to what value can they be changed to...basically with encapsulation you get to put restrictions on how and who changes your fields. For example you have: private double salary, you setter method could restrict that only hr staff can change the salary field it could be written as:

    void setSalary(Person p,double newSalary)    
    {    
    //only HR objects have access to change salary field.   
    If(p instanceof HR && newSalary>=0)    
    //change salary.   
    else   
     S.o.p("access denied");    
    } 
    

    Imagine if salary was public and could be access directly any can change it however and whenever they want, this basically the significance of encapsulation

    0 讨论(0)
  • 2020-12-08 11:40

    It's aim is nothing but protecting anything which is prone to change. You have plenty of examples on the web, so I give you some of the advantages of it:

    1. Encapsulated Code is more flexible and easy to change with new requirements
    2. Allows you to control who can access what. (!!!)
    3. Helps to write immutable class in Java
    4. It allows you to change one part of code without affecting other part of code.
    0 讨论(0)
提交回复
热议问题