简体   繁体   中英

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. 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. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM