对象交互
模拟时钟运行
一个clock类里面有两个display类,分别是时针分针,通过clock实现两个时针(对象),分针(对象)的交互.
两个对象互相不相关,通过比它们更高级的clock来实现交互
一个clock工程里面一个clock包,里边两个类,一个display类,一个clock类.
-
package clock; public class display { private int value = 0; private int limit = 0; public display(int limit) { this.limit=limit; } public void increase() { value++; if(value == limit) { value = 0; } } public int getValue() { return value; } public static void main(String[] args) { display d = new display(24); for(;;) { d.increase(); System.out.println(d.getValue()); } } }
package Clocks; public class Clock { private Display hour = new Display(24); private Display minute = new Display(60); private Display second = new Display(60); public void start() { while(true) { second.increase(); if (second.getValue()==0) { minute.increase(); if(minute.getValue()==0) { hour.increase(); } } System.out.printf("%02d:%02d:%02d\n",hour.getValue(),minute.getValue(),second.getValue()); } } public static void main(String[] args) { Clock clock = new Clock(); clock.start(); } }
参考:https://blog.csdn.net/weixin_41183791/article/details/82818115