我创建了一个Person超类来表示我在java中创建的Survivor / Infected测试游戏的基本细节。在Person SuperClass中,我有一个名为constructPersonInfo的方法,我想使用任何类型的子类对象来返回相应的类型。这是代码:
public static Person constructPersonsInfo()
{
Scanner scan = new Scanner(System.in);
System.out.println("------- please enter Persons first name -------");
String firstName = scan.nextLine();
System.out.println("------- please enter Persons last name -------");
String lastName = scan.nextLine();
System.out.println("------- please enter Persons age -------");
int age = scan.nextInt();
boolean isMaleOrFemale = false;
System.out.println("------- please enter male / female for your Persons gender -------");
String male_female = scan.nextLine();
if(male_female == "male")
{
isMaleOrFemale = true;
} else if(male_female == "female")
{
isMaleOrFemale = false;
}
Person p = new Person(firstName, lastName, age, isMaleOrFemale);
return p;
/*
the 2 lines of code above are obviously wrong, but for the life of my cannot
figure out the proper way to format the code to return either SubClass object
*/
}
主线程中的代码
public static void Main(String[] args){
Survivor s = (Survivor) Person.constructPersonInfo();
Infected i = (Infected) Person.constructPersonInfo();
}
那么我的这个美丽代码究竟是怎么做的呢?实质上,我正在尝试在SuperClass中编写一个方法,该方法可以返回任何SubClass对象的数据,具体取决于调用该方法的SubClass对象。我理解代码中令人讨厌的部分是方法被硬编码为仅返回Person对象的地方,这显然是错误的,但由于我相对较新,我需要知道正确的方法来做到这一点。谢谢大家的高级输入,当然,如果有要求,我会非常乐意提供更多信息:)
答案 0 :(得分:1)
我认为最简单的方法是预先创建对象并将其作为方法参数传递,使用setter方法设置其属性。像这样......
public static void main(String[] args) {
Survivor s = new Survivor(/* args */);
constructPersonsInfo(s);
}
public static void constructPersonsInfo(Person p) {
// ...
p.setFirstName(firstName);
p.setLastName(lastName);
p.setAge(age);
p.setMaleOrFemale(isMaleOrFemale);
}
否则,你总是可以去反思,因为按原样,施法会产生ClassCastException
。但它通常很复杂,并且不能保证根据各种因素起作用:
public static void main(String[] args) throws Exception {
Survivor s = constructPersonsInfo(Survivor.class);
}
public static <T extends Person> T constructPersonsInfo(Class<T> resultantClass)
throws NoSuchMethodException, SecurityException, IllegalArgumentException,
InstantiationException, IllegalAccessException,
java.lang.reflect.InvocationTargetException {
// ...
return resultantClass
.getConstructor(String.class, String.class, int.class, boolean.class)
.newInstance(firstName, lastName, age, isMaleOrFemale);
}