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

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

    Lets suppose you make a custom Date class with the following setters / getters:

    getDay() 
    getMonth() 
    getYear() 
    setDay() 
    setMonth() 
    setYear()
    

    Internally you could store the date using:

    private int day;
    private int month;
    private int year;
    

    Or you could store the date using a java.lang.Date-object:

    private Date date;
    

    Encapsulation doesn't expose how your class is working internally. It gives you more freedom to change how your class works. It gives you the option to control the access to your class. You can check if what the user enters is valid (you don't want the user to enter a day with a value of 32).

提交回复
热议问题