Ex3.2: Encapsulation - miguelneto1123/CES-22 GitHub Wiki
The modified code, using encapsulation, would be:
class time{
private int hour;
private int minute;
public time(int hour, int minute){
this.hour = hour;
this.minute = minute;
}
public time(){
this.time(3,45);
}
public void setHour(int hour){ this.hour = hour; }
public void setMinute(int minute){ this.minute = minute; }
public int getHour(){ return hour; }
public int getMinute(){ return minute; }
}
And another class would be needed to test the time class, in order to keep private things private:
class TimeTester{
public static void main(String args[]){
time t = new Time();
t.setTime(3);
t.setTime(25);
System.out.println("The time now is " + t.getHour() + ":" + t.getMinute());
}
}
This is better because we can prevent errors like putting hour to 35 and minutes to -13, modifying only the class's set methods (using if hour > 24 or if hour < 0, for example), assuring our object will behave the way it's supposed to behave