2.1 对象交互
2.1.1 对象的识别
数字钟
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) {
Display d = new Display(24);
for (;;) {
d.increase();
System.out.println(d.getValue());
}
}
}
2.1.2 对象交互
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) {
// TODO Auto-generated method stub
Clock clock = new Clock();
clock.start();
}
}
2.2 访问属性
2.2.1 封闭的访问属性
private
- 只有这个类内部可以访问
- 类内部指类的成员函数和定义初始化
- 这个限制是对类的而不是对对象的
2.2.2 开放的访问属性
public
- 任何人都可以访问
- 任何人指的是在任何类的函数或定义初始化中可以使用
- 使用指的是调用、访问或定义变量