Realize:
Structure:
Object: Clock-object: Hour
-Object: Minutes
- Hours and minutes have the same attribute (value, upper limit), and you can define both objects with a class display.
- But there is a connection between the two (when the minute reaches the upper limit, the hour will add 1), then another class clock to manage them;
- First, the clock class is used to define a clock object, which is used to manage two display type objects, which is the member variable of Clock (min,hour), to manage the relationship between them, and then do the display;
- Summary: There are two objects inside an object.
Package Clock:
- >>class dispaly
- >>class Clock
1 Packageclock;2 3 Public classDisplay {4 intValue = 0;5 intLimit = 0;6 7Display (intlimit) {8 This. Limit =limit;9 }Ten One voidIncrease () { A++value; - if(Value = =limit) { -Value = 0; the } - } - - intGetValue () { + returnvalue; - } + A Public Static voidMain (string[] args) {//Test atDisplay min =NewDisplay (60); - for(;;) { - min.increase (); - System.out.println (Min.getvalue ()); - } - } in -}
Display.java
1 Packageclock;2 3 Public classClock {4Display min =NewDisplay (60);5Display hour =NewDisplay (24);6 7 voidstart () {8 min.increase ();9 if(Min.getvalue () ==0) {Ten hour.increase (); One } A } - - Public Static voidMain (string[] args) { theClock Clock =NewClock (); - for(;;) { - Clock.start (); -System.out.printf ("%02d:%02d\n", Clock.hour.getvalue (), Clock.min.getvalue ()); + } - } + A}
Clock.java
Understanding the interaction of Java objects: Clock display program