I can see that a lot of you create 10 cats using a for loop, l don't get how could that work. Doesn't it create the same object all the time - cause it has the same reference - cat? To really have 10 cats isn't it necessary for them to have different references, like cat1, cat2 etc?
I passed the task by just typing it 10 times like:
Cat cat1 = new Cat();
Cat cat2…
but I'm there must be a shorter way to do it
How can you do it with for looop?
Under discussion
Comments (3)
- Popular
- New
- Old
You must be signed in to leave a comment
Dmitri
8 December 2020, 05:04
I agree, those are useless cats without the references. But still you create them and fulfill the condition.
0
Guadalupe Gagnon
7 December 2020, 14:53
Along with what Nouser said, it is an important thing for you to understand how memory is declared and assigned in computer programming. A popular analogy, and one that helped me, is thinking of memory like a handle and an attached balloon. When you create a object reference and then attach an object to that reference, it is sort of like getting a handle and then attaching a balloon to that handle, so:
In Nouser's example he creates a reference handle on line 1, then in the loop he attaches 10 cat objects to that reference. What happens is that each time a new object is created and attached to the cat handle, the object loses its attachment to that handle. Using the balloon analogy, the string attaching the prior object is removed and then a new string would be attached to the new object.
Now taking this concept a step further, consider this bit of code:
In this bit of code two handles are created, cat1 and cat2. The reference, cat1, has an object created and attached to it on line 1. On line 2 a new object is not created but instead of getting a unique object the object that was created on line 1 is attached this reference. Now you have 1 object that can be accessed by the references cat1 and cat2. Imagine 2 handles that have strings attached to the same balloon. It is important to realize that if you use one of the handles to modify the attached object, the modification would happen to the object attached to the second handle (because they are the same). A common misconceptions, and most likely a created bug, is that this bit of code is creating a copy (cat2 is a copy of cat1). 0
Nouser
7 December 2020, 13:19
this will create 10 cat objects and assign in each iteration the memory address of the created Cat object to the cat reference variable. Cause after the loop there are 9 cat objects with no reference variable pointing to them, garbage collection will take care of them and just the last instanciated object will survive.
+1