【发布时间】:2016-09-05 18:30:31
【问题描述】:
在下面的代码中,我已经声明了 room = r;主题 = s;和时间 = t;在用户定义的构造函数中,为什么必须在 set 方法中再次这样做,我的讲师特别要求我们为房间主题和时间添加 set 方法,但它是冗余代码,因为当我将其注释掉时它仍然有效。当没有使用定义的构造函数时,您只需要包含 set 方法吗?让他们在那里设置方法有什么好处?
class LectureTest{
public static void main (String [] args){
Lecture l1 = new Lecture(140, "Comp", 5);
l1.display();
Lecture l2 = new Lecture(280, "Sports", 3);
l2.display();
Lecture l3 = new Lecture(101, "Business", 5);
l3.display();
Lecture l4 = new Lecture(360, "Shooting", 4);
l4.display();
Lecture l5 = new Lecture();
l5.display();
}
}//end of LectureTest
class Lecture{
private int room;
private String subject;
private int time;
Lecture(int r, String s, int t){
room = r;
subject = s;
time = t;
}
Lecture(){}
public void setroomNumber(int r){
room = r;
}
public void setSubject(String s){
subject = s;
}
public void setTime(int t){
time = t;
}
public int getroomNumber(){
return room;
}
public String getSubject(){
return subject;
}
public int getTime(){
return time;
}
public void display(){
System.out.printf("\n" + "Room Number: " + getroomNumber() + "\n" + "Subject: " + getSubject() + "\n" + "Time " + getTime() + "\n");
}
}
【问题讨论】:
-
除非你的类型应该是不可变的,否则你需要一种方法来改变它。