Java进阶学习(2)之对象交互(上)

对象交互

  • 对象交互
    • 对象的识别
      • 时钟小程序
      • 把现实世界用对象去建模,去分解问题规模,最终抽象成对象和对象的模型
      • 例如11:03的小程序,可以抽象成一个显示类,一个类生成两个对象去表示时钟
      •  1 package com.study;
         2 
         3 public class Display
         4 {
         5     private int value=0;
         6     private int limit=0;
         7     
         8     Display(int limit)
         9     {
        10         this.limit=limit;
        11     }
        12 
        13     public int getValue()
        14     {
        15         return value;
        16     }
        17 
        18     public void increase()
        19     {
        20         value++;
        21         if(value==limit)
        22         {
        23             value=0;
        24         }
        25     }
        26     
        27     public static void main(String[] args)
        28     {
        29         Display d=new Display(24);
        30         for(;;)
        31         {
        32             d.increase();
        33             System.out.println(d.getValue());
        34         }
        35     }
        36 }

         

         时钟从0到23

    • 对象的交互
    •  1 package com.study;
       2 
       3 public class Clock
       4 {
       5 
       6     private Display hour=new Display(24);
       7     private Display minute=new Display(60);
       8     
       9     public void start()
      10     {
      11         for(;;)
      12         {
      13         minute.increase();
      14         if(minute.getValue()==0)
      15         {
      16             hour.increase();
      17         }
      18         print(hour.getValue(),minute.getValue());
      19         }
      20     }
      21     
      22     public void print(int a,int b)
      23     {
      24         System.out.printf("%02d:%02d
      ",a,b);
      25     }
      26     
      27     public static void main(String[] args)
      28     {
      29         // TODO Auto-generated method stub
      30         Clock clock=new Clock();
      31         clock.start();
      32 
      33     }
      34 
      35 }
原文地址:https://www.cnblogs.com/quxiangjia/p/12243261.html