Java 类与对象深入探究
1. 类的构造函数重载案例:Time2 类
1.1 构造函数重载概述
在 Java 中,我们可以声明自己的构造函数来指定类的对象应该如何初始化。构造函数重载允许我们提供多个具有不同签名的构造函数声明,从而以不同的方式初始化类的对象。
1.2 Time2 类的构造函数
Time2 类包含五个重载的构造函数,为对象的初始化提供了便利的方式。以下是 Time2 类的代码:
// Fig. 8.5: Time2.java
// Time2 class declaration with overloaded constructors.
public class Time2 {
private int hour; // 0 - 23
private int minute; // 0 - 59
private int second; // 0 - 59
// Time2 no-argument constructor:
// initializes each instance variable to zero
public Time2() {
this(0, 0, 0); // invoke constructor with three arguments
}
// Time2 constructor: hour supplied, minute and second defaulted to 0
public Time2(int hour) {
超级会员免费看
订阅专栏 解锁全文
1752

被折叠的 条评论
为什么被折叠?



