### Getter and setter methods

Figure 211. Direct access vs. setter method
 package hour_second.direct; public class Time { public int hour, minute; }package hour_second; import hour_second.direct.Time; public class DirectAccess { Time time = new Time(); void init() { time.hour = 17; time.minute = 45; } } package hour_second.setter; public class Time { private int hour, minute; public void setTime(int h, int m) { minute = m; hour = h; } }package hour_second; import hour_second.setter.Time; public class SetterAccess { Time time = new Time(); void init() { time.setTime(17, 45);} }

Figure 212. Why adding setter methods?
• Allow for change of implementation.

• Allow for non-business logic concerns. Examples:

• Logging

Figure 213. Implementation by minutes only
 package direct.access; public class Time { // Minutes since 00:00 public int minute; }import direct.access.Time; public class DirectAccess { final Time time = new Time(); void init() { time.minute = 720;// 12:00 } } package access.by.setter; public class Time { private int minute; // Minutes since 00:00 public void set(int h, int m) { minute = m + 60 * h; } public int getMinute(){...} // 0 to 59 public int getHour(){...} // 0 to 23 }import access.by.setter.Time; public class SetterAccess { final Time time = new Time(); void init() { time.setTime(12, 0);} } No. 93

#### Implementing getter methods

Q:

We reconsider the getter/setter based implementation in Figure 213, “Implementation by minutes only ”:

public class Time {
private int minute;   // Minutes since 00:00
public void set(int h, int m) {
minute = m + 60 * h;
}

/**
* Getting the current time's minute portion. Example: At 17:45 a value of
* 45 will be returned.
*
* @return The current time's minute portion.
*/
public int getMinute(){
... // implement me
return ...;
}

/**
* Getting the current time's hour portion. Example: At 17:45 a value of
* 17 will be returned.
*
* @return The current time's hour portion.
*/
public int getHour(){
... // implement me
return ...;
}
}

Complete the two getter methods' implementation.

### Tip

Keep in mind a day's duration being 86400 the private variable minute is ranging from 0 to 86399.

A:

package access.by.setter;

public class Time {
private int minute;   // Minutes since 00:00
public void set(int h, int m) {
minute = m + 60 * h;
}

/**
* Getting the current time's minute portion. Example: At 17:45 a value of
* 45 will be returned.
*
* @return The current time's minute portion.
*/
public int getMinute(){
return minute % 60; // 1 hour equals 60 minutes
}

/**
* Getting the current time's hour portion. Example: At 17:45 a value of
* 17 will be returned.
*
* @return The current time's hour portion.
*/
public int getHour(){
return minute / 60; // 1 hour equals 60 minutes
}
}