1

I want to create new object and to give it user input name.

Example user input "robert" wil match to:

 Action robert = new Action();
 robert.eat();

What do I need to change in the program so I can create a new object with a dynamic name? Many Thanks. I write the next code:

import java.util.Scanner;

public class Human {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner user_input = new Scanner( System.in );

        String first_name;
        System.out.print("Enter your first name: ");
        first_name = user_input.next( );//robert

        System.out.println("You are " + first_name);//robert

        Action first_name = new Action();
        Food orange = new Food();
        robert.eat(orange);

    }

}
user2879862
  • 17
  • 1
  • 2
  • 5
  • Objects don't generally have names. You're talking about the name of a *variable*, which is entirely different. If you want your object to have a name, it should have a field to remember its name, and you should probably pass the name into the constructor. – Jon Skeet Dec 03 '13 at 18:40
  • You are wrong, YOu are mixing variable name and user's name! – Abimaran Kugathasan Dec 03 '13 at 18:41
  • Why do you want to give a dynamic name to the variable if nobody is going to see it in runtime? – Math Dec 03 '13 at 18:42
  • 1
    I have a feeling you are looking for [maps](http://docs.oracle.com/javase/7/docs/api/java/util/Map.html), which allow you to access an object using a key, which can be a string. – BoppreH Dec 03 '13 at 18:42

3 Answers3

2

Java, unlike other languages, does not have a way to dynamically create variable names. Variable names are declared in the code. In order to achieve what you're trying to do, look into the Collection's Map interface. This will allow you to "map" a user given name to some value.

Quick example:

//1) Setup the mapping, 
//The first parameter to put() is the key (perhaps a user given name?) 
//and the second parameter is actual value you want to map for that key.
//note that although I'm using a String as the key and a String as the value
//You can use pretty much any object as the value. Keys are recommended to be
//immutable objects (a String is a good one)
Map<String,String> mMap = new HashMap<String,String>();
mMap.put("John", "Orange");
mMap.put("Steve","Apple");

//2) Once the map is setup, you can then retrieve values given a key:
System.out.println("John's fruit is: "+mMap.get("John"));

More info here.

Carlos N
  • 1,616
  • 14
  • 15
0

Variable names cant be specified(created) at run time(dynamically).

4J41
  • 5,005
  • 1
  • 29
  • 41
0

This is not possible. How can you declare the name of the Class object as a variable.