1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
15 # This module provide a simple wall clock.
16 # It is an example of getters and setters.
17 # A beefed-up module is available in clock_more
20 # A simple wall clock with 60 minutes and 12 hours.
22 # total number of minutes from 0 to 719
23 var total_minutes
: Int
24 # Note: only the read acces is public, the write access is private.
26 # number of minutes in the current hour (from 0 to 59)
27 fun minutes
: Int do return self.total_minutes
% 60
29 # set the number of minutes in the current hour.
30 # if m < 0 or m >= 60, the hour will be changed accordinlgy
31 fun minutes
=(m
: Int) do self.total_minutes
= self.hours
* 60 + m
33 # number of hours (from 0 to 11)
34 fun hours
: Int do return self.total_minutes
/ 60
36 # set the number of hours
37 # the minutes will not be updated
38 fun hours
=(h
: Int) do self.total_minutes
= h
* 60 + minutes
40 # the position of the hour arrow in the [0..60[ interval
41 fun hour_pos
: Int do return total_minutes
/ 12
43 # replace the arrow of hours (from 0 to 59).
44 # the hours and the minutes will be updated.
45 fun hour_pos
=(h
: Int) do self.total_minutes
= h
* 12
47 redef fun to_s
do return "{hours}:{minutes}"
49 fun reset
(hours
, minutes
: Int) do self.total_minutes
= hours
*60 + minutes
51 init(hours
, minutes
: Int) do self.reset
(hours
, minutes
)
55 # Note: o is a nullable Object, a type test is required
56 # Thanks to adaptive typing, there is no downcast
57 # i.e. the code is safe!
58 return o
isa Clock and self.total_minutes
== o
.total_minutes
62 var c
= new Clock(10,50)
63 print
"It's {c} o'clock."
66 print
"Now it's {c} o'clock."
68 print
"The short arrow in on the {c.hour_pos/5} and the long arrow in on the {c.minutes/5}."
71 print
"Now it's {c} o'clock."
73 var c2
= new Clock(9, 11)
74 print
"It's {c2} on the second clock."
75 print
"The two clocks are synchronized: {c == c2}."
77 print
"It's now {c2} on the second clock."
78 print
"The two clocks are synchronized: {c == c2}."