我希望能够根据用户输入动态创建员工对象。我已经开设了两个不同的类(class),一个是经理,一个是助理。我应该能够输入我想要创建的员工类型以及员工的姓名和年龄。 我怎样才能做到这一点?
while (true){
System.out.print("Input the type of employee: ");
String type = Input.next();
//Can only be "manager" or "associate"
System.out.print("Input the name of the employee: ");
String name = Input.next();
System.out.print("Input the age of the employee: ");
int age = Input.nextInt();
/*The name of the object should also be the name of the employee
*Depending on what "Type" is given from the user determines what type of object the new object is going to be
*/
type name = new type(name,age)
//type is not the reference type but a variable holding the reference *type
*/
}
我希望我能够创建任意数量的引用类型的对象:管理器或关联器。不同的名字和年龄
最佳答案
不能使用字符串变量作为类名。而不是
type name = new type(name,age)
尝试
if ("manager".equals(type)) {
Manager mgr = new Manager(name, age);
} else {
Associate asc = new Associate(name, age);
}
这假设您在某处定义了 Manager
和 Asssociate
类,并且它们每个都有一个采用 String
和 的构造函数int
.
关于java - 如何在 Java 中使用用户输入引用类型、对象名称和参数在运行时创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58695574/