2.1对象交互
Display.java
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) {
// TODO Auto-generated method stub
Display d = new Display(24);
for(;;) {
d.increase();
System.out.println(d.getValue());
}
}
}
运行结果的一部分
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
0
1
2
3
4
5
6
7
这里的代码结构
clock.java
package clock;
public class Clock {
private Display hour = new Display(24);
private Display minute = new Display(60);
public void start() {
while(true) {
minute.increase();
if(minute.getValue() == 0) {
hour.increase();
}
System.out.printf("%02d:%02d\n", hour.getValue(),minute.getValue());
}
}
public static void main(String[] args) {
Clock clock = new Clock();
clock.start();
}
}
运行结果
01:59
02:00
02:01
02:02
02:03
02:04
02:05
02:06
02:07
02:08
02:09
02:10
02:11
02:12
02:13
02:14
02:15
02:16
02:17
02:18
02:19
02:20
02:21
02:22
02:23
02:24
02:25
02:26
02:27
02:28
02:29
02:30
02:31
02:32
02:33
02:34
02:35
02:36
02:37
02:38
02:39
02:40
02:41
02:42
02:43
02:44
02:45
02:46
02:47
02:48
02:49
02:50
02:51
02:52
02:53
02:54
02:55
02:56
02:57
02:58
02:59
03:00
03:01
03:02
03:03
03:04
03:05
03:06
03:07
03:08
03:09
03:10
03:11
03:12
03:13
03:14
03:15
03:16
03:17
03:18
03:19
03:20
03:21
03:22
03:23
03:24
03:25
03:26
03:27
03:28
03:29
03:30
03:31
03:32
03:33
03:34
03:35
03:36
03:37
03:38
03:39
03:40
03:41
03:42
03:43
03:44
2.2访问属性
同一个类的所有不同的对象之间,可以访问其他对象的私有成员。。因为私有,是针对类而言。
如果一个类,想在其他所有类中都可以用,那么这个类必须用public
而在一个java文件中,public的,只能有一个。
2.3 包
在下面的情况里,import的是display这个包里的,Display这个类
2.4 类变量
这里通过step这个变量,来解释“类变量”
package clock;
public class Display {
private int value = 0;
private int limit = 0;
private static int step = 1;
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) {
// TODO Auto-generated method stub
Display d1 = new Display(10);
Display d2 = new Display(20);
d1.increase();
System.out.println(d1.getValue());
System.out.println(d2.getValue());
System.out.println(d1.step);
System.out.println(d1.step);
d1.step = 2;
System.out.println(d1.step);
System.out.println(d1.step);
}
}