java - 如何使用相同的父类(super class)方法初始化不同的子类类型?

标签 java casting polymorphism subclass superclass

我创建了一个 Person 父类(super class)来表示我在 java 中创建的幸存者/感染测试游戏的基本细节。在 Person SuperClass 中,我有一个名为 ConstructionPersonInfo 的方法,我想使用任何类型的子类对象来返回相应的类型。这是代码:

 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();
}

那么我这段漂亮的代码到底想做什么呢?本质上,我试图在父类(super class)中编写一个方法,该方法可以返回任何子类对象的数据,具体取决于哪个子类对象调用该方法。我知道代码中令人讨厌的部分是方法被硬编码为仅返回 Person 对象,这显然是错误的,但由于我相对较新,我需要知道执行此操作的正确方法。感谢大家提前提供的信息,当然,如果需要,我非常乐意提供更多信息:)

最佳答案

我认为最简单的方法是预先创建对象并将其作为方法参数传递,使用 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);
}

关于java - 如何使用相同的父类(super class)方法初始化不同的子类类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32428625/

相关文章:

java - 从 Mongodb 中过滤 Java 对象

java - 读取文件方向/路径Java

java - 如何将sql azure数据检索到 ListView 中?

c - 使用armcc时为"Error #119: cast to type <..> is not allowed"

java - 在 equals 方法中类型转换

C++ 从抽象基类指针复制数据?

java - 使用网格/节点在多个虚拟机上运行并行 Selenium 测试

c# - 浮点值在 Int 中丢失

c++ - 我明白为什么了,但是 Virtual Functions/VTables 到底是如何允许通过指针访问正确的函数的呢?

编译时的 C++ 类型检查