This is a simple question (I think)
Lets say I have this code (Assuming I have a dog class)
String name = "dog";
dog name = new dog();
How can I get java to recognize name as a String and name the object dog?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
While you can do what you’re trying in some scripting languages such as PHP (and this question is often asked by many PHP programmers who start Java), this is not how Java works, and in fact variable names are a much less important than you may realize and hardly even exist after code is compiled. What is much more important and what is key are variable references — the ability to gain access to a particular object at a particular point in your program, and you can have Strings refer to objects easily by using a Map as one way.
For example
Or you can gain references to objects in many other ways such as via arrays, ArrayLists, LinkedLists, or several other collectinos.
Edit
You state:
This is exactly what I meant when I said that the name of the variable is not as important as you think it is. The variable name is not the “object name” (this really doesn’t exist in fact).
For example if you create a dog in a variable named Fido, and then assign it to a new variable named spot, both variables, despite having different names will refer to the very same object:
If you want to give a variable a “name” consider giving the class a name property:
Now you can give each Dog object its own (semi) unique name if you wish.