我已根据父类创建了三个子类。
当我的程序运行时,其中一个子类将被实例化,并且我有一些操作需要非null子对象。
以下是我的代码的一些示例:
父:
public class Person {
// code here
doMore(Operation operation) {
//code here
}
}
操作类:
public class Operation {
Person person;
public Operation(Person person) {
this.person = person;
}
}
儿童班:
public class Doctor extends Person {
// code here
}
public class Lawyer extends Person {
// code here
}
public class Pilot extends Person {
// code here
}
主程序:
// String temp is calculated
Doctor doctor = null;
Lawyer lawyer = null;
Pilot pilot = null;
if (temp.equals("doctor")) {
doctor = new Doctor();
Operation operation = new Operation(doctor);
doctor.doMore(operation);
} else if (temp.equals("lawyer")) {
lawyer = new Lawyer();
Operation operation = new Operation(lawyer);
lawyer.doMore(operation);
} else {
pilot = new Pilot();
Operation operation = new Operation(Pilot);
pilot.doMore(operation);
}
正如您所看到的,根据temp的值,只会实例化三个子类中的一个,并且只有一个对象将为非null。
我还有两个操作,在实例化后将使用新创建的对象。现在,重复相同的两行三次似乎是多余的。
有没有办法简化这个,所以这两行只使用一次?我可以在这里使用一些继承功能吗?
答案 0 :(得分:2)
Person person = null;
if (temp.equals("doctor")) {
person = new Doctor();
} else if (temp.equals("lawyer")) {
person = new Lawyer();
} else {
person = new Pilot();
}
Operation operation = new Operation(person);
person.doMore(operation);
由于Person
是所有三个类都实现的接口,因此您可以将它们全部视为Person
。
为了它的价值,我会写一个enum
来封装你要比较的字符串并写一个switch
语句。也就是说,你也可以在字符串上switch
:
switch (temp) {
case "doctor": break;
case "lawyer": break;
default: break;
}