Java设计一个clock类并用封装的思想
时间: 2024-06-12 15:08:11 浏览: 62
用Java编写的时钟类
public class Clock {
private int hours;
private int minutes;
private int seconds;
public Clock(int hours, int minutes, int seconds) {
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
}
public int getHours() {
return hours;
}
public void setHours(int hours) {
this.hours = hours;
}
public int getMinutes() {
return minutes;
}
public void setMinutes(int minutes) {
this.minutes = minutes;
}
public int getSeconds() {
return seconds;
}
public void setSeconds(int seconds) {
this.seconds = seconds;
}
public void tick() {
seconds++;
if (seconds == 60) {
seconds = 0;
minutes++;
}
if (minutes == 60) {
minutes = 0;
hours++;
}
if (hours == 24) {
hours = 0;
}
}
public String toString() {
return String.format("%02d:%02d:%02d", hours, minutes, seconds);
}
}
这个Clock类封装了小时、分钟、秒钟这三个属性,同时提供了公共的getter和setter方法,使得外部类可以访问和修改这些属性。tick()方法用于模拟时钟的运行,每次调用会让时钟的秒数加1,如果加到60就会进位到分钟,再到小时,最后时钟会在24小时后回到0点。toString()方法用于返回一个格式化的字符串表示时钟当前的时间。
阅读全文