Java,是否有可能将对象从子类"转换"为超类中的对象

ved*_*ran 8 java subclass object superclass

我有两个班级学生和导师.导师基本上是一名具有教师ID的学生(导师扩展学生).一旦他的合同完成,他就会重新成为一名学生.那么我能以某种方式将他转回他的"前一卷"学生吗?

Bra*_*rad 5

你真正想要做的是使用组合而不是继承.将所有对象保留为类型Student,然后临时TutorRole为每个实例分配a的行为Student.

使用此设计,您的Student类将包含TutorRole可在运行时添加或删除的类型的属性(成员变量).通过添加isTutor()方法,您可以在运行时以清晰简洁的方式确定学生是否为导师.

TutorRole课程将封装的是一个导师的行为(即方法).

/*
 * The TutorRole can be set at runtime
 */
public class Student {

    private String facultyId;

    private TutorRole tutorRole = null;

    public boolean isTutor() {
        return !(tutorRole == null);
    }

    public void doTutorStuff() {
        if(isTutor()) {
            tutorRole.doTutorStuff();
        }
        else {
            throw new NotTutorException();
        }
    }

    public void setTutorRole(TutorRole tutorRole) {
        this.tutorRole = tutorRole;
    }
}

/*
 * Ideally this class should implement a generic interface, but I'll keep this simple
 */
public class TutorRole {

    public void doTutorStuff() {
        // implementation here
    }
}

/*
 * Now let's use our classes...
 */
Student st = new Student(); // not a tutor
st.setTutorRole(new TutorRole()); // now a tutor
if(st.isTutor()) {
    st.doTutorStuff();
}
st.setTutorRole(null); // not a tutor anymore
Run Code Online (Sandbox Code Playgroud)

另一种方法是让一个Tutor类包含对Student对象的引用,但它取决于您将如何与Student和Tutor对象进行交互,以此来编写此代码.