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

前端 未结 15 2080
情深已故
情深已故 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

    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

提交回复
热议问题