Reputation: 29
Say I have objects:
Animal lion = new Animal();
Animal elephant = new Animal();
Animal cheetah = new Animal();
How would I be able to store the names of the animals (i.e. lion, elephant, cheetah)?
I have tried using
for (int count = 0; count < 3; count++) {
String name = lion.getClass().getName();
but this would only give me "Animal.lion", when I only want the "lion" bit.
Thanks in advance!
Upvotes: 1
Views: 83
Reputation: 11
I don't know exactly why you need the "name" of the variable for but to solve your specific problem: as the expression "String name = lion.getClass().getName();" is giving you "Animal.lion" back, you can split that string(name) and take the second part of the resulting array.
like:
Upvotes: 0
Reputation: 285460
Objects don't have "names". You are confusing object with variable, and inflating the importance of variables. What matters is not so much the variable, but rather the reference.
If you want to associate an object with a String, then use a Map.
e.g.,
Map<String, Animal> animalMap = new HashMap<String, Animal>();
Animal lion = new Animal();
animalMap.put("lion", lion);
Animal elephant = new Animal();
animalMap.put("elephant", elephant);
Animal cheetah = new Animal();
animalMap.put("cheetah", cheetah);
then
for (String key : animalMap.keySet()) {
System.out.printf("Animal name is %s%n", key);
}
Also note that as hakiko states well (1+ to his answer), an object can be referred to by multiple variables, and in that situation, which variable represents the "name" of the object??
Upvotes: 5
Reputation: 1805
You can slightly change the class Animal
.
class Animal
{
private String nameOfAnimal;
public Animal(String nameOfAnimal)
{
this.nameOfAnimal=nameOfAnimal;
}
public String getName()
{
return nameOfAnimal;
}
}
class Main
{
public static void main(String args[])
{
Animal lion=new Animal("lion");
Animal elephant=new Animal("elephant");
Animal cheetah=new Animal("cheetah");
System.out.println(lion.getName());
System.out.println(elephant.getName());
System.out.println(cheetah.getName());
}
}
INPUT:NOTHING
OUTPUT:
lion
elephant
cheetah
Upvotes: 2
Reputation: 6527
No, there is no way to do this. The name you give the variable that refers to that object instance is not known to the object.
Consider that you could create multiple variables which ALL had references to the same object; the idea of "the name of" the object instance is meaningless, and this case illustrates that.
You can create a field in an object that contains a name, and assign that name when you create the object, and then retrieve that if you want to.
public class Television
{
private String name = null;
public String getName() { return name; }
public void setName(String givenName) { name = givenName; }
public Sample(String givenName) { setName(givenName); }
// add whatever you want to this class
}
Upvotes: 2