Encapsulation Vs Plain

前端 未结 4 1879
你的背包
你的背包 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: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.

提交回复
热议问题