A simple question on Java class
I want to create my class with my own add method which adds an object of a different class.
For eg if my class name is Weapon, I want to create an add method like void add(Gun gun) (Gun being one of my other classes for example)
This would be just like creating your own collection maybe??? if I am not wrong? Like list.add() method, I want to implement my own add method for the Weapon class
So when I instantiate an object of my weapon class, it should be like Weapon w = new Weapon(new Gun( ... .. constructor parameters) )
Also I would like to have variants of my add methods. Like a different add method with different parameters like void add(Weapon weapon) ( creating an method to add your own class object )
So I am not sure if this is similar to implementing a collection?? And if it is how do I achieve it? Do I have to extend another class for this?
Apologies if my question confused anyone! :)
add()method, what stops you from writing one? What does it has to do with collections?Weapon w = new Weapon(new Gun(...))doesn't really make sense to me. On the other hand,Weapon w = new Gun(...)does.Collection, unless all the objects you are trying to add are based from a common parent, then it might be, but considering you are trying to provide functionality different objects types, I'd personally avoid it. Instead, I would use aListinternally for each type of object you want to included, assuming you can have more than one.Weaponist not only similar to, but actually the same as the behavior of Collections (as I understood), why do you want to reimplement it? Just reuse the classes the Java API offer. Extending is an option, but also just adding a collection as a class member is easy to implement.