[英]How to create an object during runtime with user input reference type, object name and parameters in Java
I want to be able to dynamically create an employee object from user input.我希望能够根据用户输入动态创建员工 object。 I have two different classes made already one being a manager and one being an associate.我有两个不同的班级,一个是经理,一个是助理。 I should be able to input what type of employee I want to create and the name and age of the employee.我应该能够输入我想要创建的员工类型以及员工的姓名和年龄。 How can I do this?我怎样才能做到这一点?
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
*/
}
I expect that I should be able to create as many objects as I want of either reference type: manager or associate.我希望我应该能够创建任意数量的引用类型的对象:管理器或关联。 With different names and ages有不同的名字和年龄
You cannot use a String variable as a class name.您不能将字符串变量用作 class 名称。 Instead of代替
type name = new type(name,age)
try尝试
if ("manager".equals(type)) {
Manager mgr = new Manager(name, age);
} else {
Associate asc = new Associate(name, age);
}
This assumes you have the classes Manager
and Asssociate
defined somewhere and they each have a constructor that takes a String
and an int
.这假设您在某处定义了类Manager
和Asssociate
,并且它们每个都有一个构造函数,该构造函数接受一个String
和一个int
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.