package cen.col.course.demo;
import java.io.Serializable;
public class Course implements Serializable {
private static final long serialVersionUID = 1L;
protected String code;
protected String title;
protected Professor professor;
public Course( String code) throws InvalidDataException {
super();
setCode(code);
}
public Course(String code, String title ) throws InvalidDataException {
this(code);
setTitle(title);
}
public Course(String code, String title, Professor professor) throws InvalidDataException {
this(code,title);
setProfessor(professor);
}
public String getCode() {
return code;
}
protected void setCode(String code) throws InvalidDataException {
if ( code == null || code.length() < 1) {
throw new InvalidDataException("Course must have a course code");
}
this.code = code;
}
public String getTitle() {
return title;
}
public void setTitle(String title) throws InvalidDataException {
if ( title == null || title.length() < 1) {
throw new InvalidDataException("Course must have a title");
}
this.title = title;
}
public Professor getProfessor() {
return professor;
}
public void setProfessor(Professor professor) {
this.professor = professor;
}
public String toString() {
String output = getCode() + ": [" + getTitle() + "]";
if (getProfessor() != null ) {
output += " is taught by " + getProfessor();
}
return output;
}
public boolean equals(Course c) {
if ( ! this.getCode().equals(c.getCode())){
return false;
}
if ( ! this.getTitle().equals(c.getTitle())){
return false;
}
// should the prof field be included in test for equality?
if ( ! this.getProfessor().equals(c.getProfessor())){
return false;
}
return true;
}
}
我有三个问题:
我注意到我的教授从构造函数中调用了 setter 方法。我做了一些搜索,对此有不同的想法。有人说可以,有人说使用子类时要小心,可以从构造函数中调用setter吗?
构造函数抛出异常,因为她正在从构造函数调用 setter。现在我的问题是,如果从构造函数调用设置器不是一种安全的方法,那么正确的方法是什么?我的猜测是声明一个无参数构造函数,并使用 setter 构建对象。
我想这样做,是不可能的?
Course createCourse = new Course("1234","Programming 1","Pam Halpert");
我正在调用带有 3 个参数的构造函数,但是,如果从构造函数调用 setter 是不安全的,那么将如何执行此操作并设置异常?我可以使用 if 语句吗?检查某些内容是否为空白并在必要时抛出异常?