I'm currently reading Sam Teach Yourself Java in 21 days 6th Edition by Rogers Cadenhead.
There is an example in the book that shows object creation using a for loop in one of the chapters on static variables and methods.
The code is as follows:
public class InstanceCounter {
private static int numInstances = 0;
protected static int getCount() {
return numInstances;
}
private static void addInstance() {
numInstances++;
}
InstanceCounter() {
InstanceCounter.addInstance();
}
public static void main(String[] arguments) {
System.out.println("Starting with " +
InstanceCounter.getCount() + " objects");
for (int i = 0; i < 500; ++i)
new InstanceCounter();
System.out.println("Created " +
InstanceCounter.getCount() + " objects");
}
}
I do not understand how the for loop can create objects without actually giving these 500 new objects names. This is how I have been taught to create objects:
Object Objectname = new Object();
Is the for loop just going to create these objects and discard them straight afterwards as they have no Objectname?
I see that when I type the code into Netbeans, the hint says "New Instance ignored".
T x = new T()causes a new instance ofTto be referenced by the variablex. It's pretty much like keeping track of the objects you create on a piece of paper. If you don't write it down then it will still exist but you can't pinpoint it because it can't be named; if you do write it down you can refer to it by the name you gave it in your list.