编写3个类,类名分别为Clock、A、B,其中类Clock和类A放在同一个包packone中,而类B则放在另一个包packtwo中,包packone和包packtwo放在同一个目录下。类Clock中有3个整型数据hour、minute、second,它们分别是public、private、protected,类Clock还包含一些方法使用这些数据,方法的设计可自由发挥。
时间: 2023-07-14 15:13:32 浏览: 109
以下是类的代码实现:
Clock类:
```java
package packone;
public class Clock {
public int hour;
private int minute;
protected int second;
public Clock(int h, int m, int s) {
hour = h;
minute = m;
second = s;
}
public void setTime(int h, int m, int s) {
hour = h;
minute = m;
second = s;
}
public String getTime() {
return String.format("%02d:%02d:%02d", hour, minute, second);
}
}
```
A类:
```java
package packone;
public class A {
public static void main(String[] args) {
Clock clock = new Clock(12, 30, 0);
clock.setTime(16, 45, 30);
System.out.println(clock.getTime());
}
}
```
B类:
```java
package packtwo;
import packone.Clock;
public class B {
public static void main(String[] args) {
Clock clock = new Clock(12, 30, 0);
// clock.minute = 45; // Error: minute has private access in Clock
// clock.second = 30; // Error: second has protected access in Clock
clock.hour = 16; // OK: hour is public in Clock
System.out.println(clock.getTime());
}
}
```
注意,在B类中,我们需要使用`import packone.Clock;`语句来导入Clock类。在B类中,我们无法直接访问Clock类中的minute和second变量,因为它们的访问修饰符是private和protected,但是我们可以访问hour变量,因为它的访问修饰符是public。
阅读全文