定义北京时间类BeijingTime,成员变量有时、分、秒,构造方法重载以及显示时间的方法。
class BeijingTime{
private int hour; //时
private int min; //分
private int sec; //秒
public BeijingTime() { //构造方法
this.hour=0;
this.min=0;
this.sec=0;
}
public BeijingTime(int hour,int min,int sec) { //构造方法重载
this.hour=hour;
this.min=min;
this.sec=sec;
}
public void display() {
System.out.print("北京时间:");
if(hour<10) {
System.out.print("0"+hour+":");
}
else {
System.out.print(hour+":");
}
if(min<10) {
System.out.print("0"+min+":");
}
else {
System.out.print(min+":");
}
if(sec<10) {
System.out.println("0"+sec);
}
else {
System.out.println(sec);
}
}
void setBeijingTime(int hour,int min,int sec) {
this.hour=hour;
this.min=min;
this.sec=sec;
}
}
public class TestBeijingTime {
public static void main(String[] args) {
BeijingTime bt,bt1;
bt=new BeijingTime(); //默认参数为0
bt1=new BeijingTime(9,2,5);
bt.display();
bt1.display();
bt.setBeijingTime(0, 25, 34);
bt.display();
}
}
输出样例: