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;
}
}
我有三个问题:
Course createCourse = new Course("1234","Programming 1","Pam Halpert");
我正在调用带有 3 个参数的构造函数,但是,如果从构造函数调用 setter 是不安全的,那么将如何执行此操作并设置异常?我可以使用 if 语句吗?检查某些内容是否为空白并在必要时抛出异常?
最佳答案
关于Java - 来自构造函数的 setter ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12533247/