是否可以将对象的 class 转换为另一个对象?

Is it possible to convert an object's class to another?

假设我们有三个 classes:Person、Student extends Person 和 OfficeWorker extends Person。

public class Person{
   //fields and methods, especially constructor & getter-setter methods
   private String occupation;
}
public class Student extends Person{
   private int education;
   //Constructor assigns education zero to a student
   public void dailyEducation(){
      this.education++;
   }
   public void finishEducation(){
      this.education = "Office Worker";
      //_________________________________
   }
}
public Class OfficeWorker extends Person{
   //own fields and methods
}
public class mainF{
   //typical psvm(s[]a)
}

那么我应该在 Student class 或什至在 main 函数中的空白处输入什么,才能将这个人(学生)变成 OfficeWorker?

一种方法:

interface Person {
    String getOccupation();
}

class Student implements Person {

    @Override
    public String getOccupation() {
        return "student";
    }
}

class OfficeWorker implements Person {

    @Override
    public String getOccupation() {
        return "office worker";
    }
}

class LifetimePerson implements Person {
    private Person currentRole = new Student();

    @Override
    public String getOccupation() {
        return currentRole.getOccupation();
    }
    
    public void finishEducation() {
        currentRole = new OfficeWorker();
    }
}

但是当finishEducation()当了上班族又接到电话怎么办?我们是抛出异常,还是忽略异常?

这是否是一种有用的方法取决于您的要求的详细信息。