| Author |
naming a class instance
|
andy hough
Greenhorn
Joined: Dec 12, 2006
Posts: 6
|
|
Hi. I have created a class DList. Now, to create a new instance of this class the code is: DList myFirstDList = new DList(); ok so far, I understand this, however, I want to be able to create multiple instances of DList automatically using a for loop kinda like the code below: for(count=0; count<5; count++) { DList count = new DList(); } I had though I would get 5 instances of DList called: 0 1 2 3 and 4. However, I get a message about count already being assigned. Can anyone help?
|
 |
Jaime M. Tovar
Ranch Hand
Joined: Mar 28, 2005
Posts: 133
|
|
Maybe in an array: DList [] dlist = new DList(5); for(count=0; count<5; count++) { dlist[count] = new DList(); } The error you get is because you are using the same variable name twice in the same code segment. count for the 'for' and count for the object instance.
|
She will remember your heart when men are fairy tales in books written by rabbits.<br /> As long as there is duct tape... there is also hope.
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24061
|
|
Hi Andy, Welcome to JavaRanch! The specific error message here is telling you that you've already used "count" for the name of an int variable, and you can't reuse it in the same scope for the name of another variable. But I think what you're trying to invent is called an array. An array is an ordered collection of objects. It has a definite length, and each item in the array has an index, which starts at 0 and is just the position of that item in the array. You can create an array of 5 DList objects like this: Then you could, for example, print the third DList like this: System.out.println(dlists[2]); You can learn more about arrays from your textbook.
|
[Jess in Action][AskingGoodQuestions]
|
 |
Joanne Neal
Rancher
Joined: Aug 05, 2005
Posts: 3011
|
|
Originally posted by Jaime Tovar: Maybe in an array: DList [] dlist = new DList(5);
That should be
|
Joanne
|
 |
andy hough
Greenhorn
Joined: Dec 12, 2006
Posts: 6
|
|
excellent thanks. I'm quite familiar with arrays but to be honest had not even considered using them in this way! I shall try it out this evening!
|
 |
 |
|
|
subject: naming a class instance
|
|
|