Clock

Learning object recognition and object interaction, a class member variables can be other class object, an object can be composed of other classes of objects, this object can be made him realize the interaction between the composition of the object.(From Youdao Dict)

学习内容:

学习了对象的交识别和对象的交互,一个类的成员变量可以是其他类的对象,一个对象可以由其他类的对象组成,这个对象可以使他的组成对象之间实现交互。

代码描述:

minute从0开始增加,加到59时然后归零,并与hour交互,每次归零,hour加 1 ,最后格式化输出类型“00:00”

练习代码如下:

public class Clock {
    private Display hour = new Display(24);//创建一个Display的对象hour(带入参数)
    private Display minute = new Display(60);//创建一个Display的对象minute(带入参数)
    //开始走时间的函数(Clock的成员函数)
    public void start() {
        minute.increase();
        //如果分钟值变为零,小时值加一
        if (minute.getValue() == 0) {
            hour.increase();
        }
        //格式化打印输出
        System.out.printf("%02d:%02d", hour.getValue(), minute.getValue());
        System.out.println();
    }
//主函数
    public static void main(String[] args) {
        Clock clock = new Clock();//创建对象clock
        for (; ; ) {
            clock.start();
        }
    }
    //创建类Display
    class Display {
        private int limit = 0;
        private int value = 0;
        //函数重载
        public Display(int limit) {
            this.limit = limit;
        }
        //值增加,达到limit时重置为0
        public void increase() {
            value++;
            if (value == limit) {
                value = 0;
            }
        }
        //返回value值
        public int getValue() {
            return value;
        }
    }
}

描述关系如下图

类型名称 Display

接口 value
接口 limit
接口 incraease
接口 getValue

类型名称 Clock

接口 hour (Display类的对象)
接口 minute (Display类的对象)

对于对象clock,属于Clock类,由两个Display的对象组成,分别是hour、minute。

posted @ 2020-06-12 07:49  juyss  阅读(534)  评论(0编辑  收藏  举报