Encapsulation

It is recommended to set access modifier limited scope to maintain code well.

The reason why we use access modifier is 1. to protect data from outside and 2. hide internal data that is unnecessary in outside. Rather than direct access to member variable, it is available to access to member variable via method.

public class Time {
    //set access modifier as private so that it is non-accessible from outside.
    private int hour;
    private int minute;
    private int second;
    
    public int getHour() {return hour;}
    public int setHour(int hour) {
        if(hour < 0 || hour > 23) return;
        this.hour = hour;
    }
    
}

Last updated