John Smith
John Smith

Reputation: 87

Creating "noname" class instances

So here is my problem. I know one of the simpliest way of creating a new instance of a class is :

    ClassName instanceName = new ClassName(); 
    instanceName.methodName(); //executing the method

The problem I am facing is this, I want the instances to be created automatically for example when I click a button a new instance is made, how do I do that? Should I create some automated method with iterating variable to create new instances like instance1, instance2 etc.? I also tried to do something like this, already executing the method with creation of a new instance:

    (new ClassName()).methodNAme();

However I have no access to this new instance, because I don't know how to call/pass it since it has no name. Thank you for any help.

Upvotes: 0

Views: 427

Answers (1)

Antimony
Antimony

Reputation: 39451

Variables can be reassigned. The variable is a name which can point to different instances at runtime. So you only need a single variable if you only want the most recent instance.

ClassName instanceName;

//Create a new instance
instanceName = new ClassName(); 
instanceName.methodName();

//Create a new instance
instanceName = new ClassName(); 
instanceName.methodName(); //Will now use the second instance

Upvotes: 1

Related Questions