Hey folks.

I'm trying to make a new Fruit object each time aMethod is called.
The new Fruit object's name must be unique.

The problem is that the name of this Fruit object is the same name as one of the parameters of aMethod - this name is unfortunately the best name for the new object I think.

What can I do make it work?
Whatever the new Fruit object is called, the name must contain whatever is passed to aMethod.

Please help!

public void aMethod (String someFruit){
    Fruit someFruit = new Fruit(someFruit);    

}
//The Fruit object's name is the same name as the parameter. 
//The parameter passed to Fruit is the String that's provided to this method (aMethod). 

Recommended Answers

All 2 Replies

What exactly do you mean by the object's name? Objects in Java do nor have names. You can have an instance variable String name; in the Fruit class and set that.

... part 2
if you want to create a reference variable with that name then the answer is "you can't". Even if there were a way to do that, there's no way to use a variable whose name isn't known at compile time (ignoring advanced Reflection techniques).

If you want to be able to refer to your Fruit objects based on their name, then you can use a Map, eg

HashMap<String, Fruit> namedFruit = new HashMap<String, Fruit>();
namedFruit.add("Apple",  new Fruit("Apple"));
Fruit f = namedFruit.get("Apple");
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.