I am trying to figure out if there is a way to add a newly created object to an ArrayList in a constructor. It seems that I cannot get it to work the way I would like because really the object is not yet created when it is trying to do it. Is it ever possible and if so is it ever done or is it not proper?
Those are the main() and the constructor which gets called where I would like to add the new objects to the ArrayList.
Bobby Smallman wrote:
You are passing dog0 as constructor parameter and assigning the object instance back to dog0.
What you are trying to do?
What is the problem you are trying to solve?
Shouldn't it be
Animal shouldn't know about the List, so it shouldn't pass the List as constructor parameter.
Bobby Smallman wrote:You can absolutely do that. But I was trying to make the adding of the animal object to the ArrayList in the constructor of the object to streamline the creation of the object. It isn't a big deal to do a animals.add(Animal) for each of the objects in main when there are only a couple of them, but wouldn't running it in the constructor streamline the process for when you have TONS of entries?
So you are trying to get rid of typing many animals.add(Animal)?
Let say I have an object called BankAccount, if I pass the bankAccountList to constructor ?
to expose the bankAccount details belong to other bank accounts?
Actually the code could compiles, but this shouldn't be a good design, right ?
If you want to reduce lines of code, you could do
Or you could do
What are you trying to achieve? I think that what you are trying to do is somehow store all the animals created in an ArrayList? Is that correct?
If yes, then first of all, this ArrayList should belong to the class instead of instances of the class - so it should be marked as static.
Then from the constructor you can call arrayList.add(this)
A static member belongs to the class rather than a particular object. Each object has it's own copy of non-static objects - however, there is just one copy of a static member which is shared between all instances of that class. Further, a static member is associated with a class. So, existence of a static member depends only on the existence of a class and a static member is accessed as ClassName.staticMemberName. Thus, static members DO NOT need objects to access them.
this keyword refers to the current instance as already pointed by Ernest. You were trying to pass the animal reference but actually it was the object that you needed access to and using "this" you can access that instance.
Now when you create a new animal, it will automatically be added to the ArrayList animals. You can write more methods to access the ArrayList and you may also mark it as final to make sure that all instances access the same ArrayList and do not create a new one and assign that by mistake.
Again, the code above might not be what you are expecting because I haven't really understood your question or rather your purpose well.