This site requires JavaScript, please enable it in your browser!
Greenfoot back
Razzo
Razzo wrote ...

2012/10/14

how would I create a new instance of a Already defined object?

Razzo Razzo

2012/10/14

#
how would I create a new instance of a Already defined object? On mouse click I want to create a new instance of whatever Actor is in my ArrayList (Inventory) at index (int selected) Here is what I got so far..
//This code will Activate on mouse click
RangedWeapon x = (RangedWeapon)inventory.get(selected);
// Gets the object, so It's modular to all weapons
getWorld().addObject(y, getX(), getY());
//I want y to be a new instance of what ever x is.
SPower SPower

2012/10/14

#
You need to get the class and ask it for a new instance. Note that this only works when the class has a constructor without arguments,
Class c = <the object in the list>.getClass();
try {
    Actor y = (Actor) c.getInstance();
    // do the rest of your code
catch (Exception e) {}
Razzo Razzo

2012/10/14

#
The class I am using has a Constructor with arguements! D: What can I do ?
danpost danpost

2012/10/14

#
You can only use 'newInstance' to create an object in a class that has a constructor with zero arguments. You can add a constructor with no arguments (thereby using default values) and then add method(s) to pass in the specifics (arguments).
Razzo Razzo

2012/10/14

#
If there is no way, How could I set it up? Every Ranged Weapon has 2 int arguments in their constructor, If the mouse is clicked I want ArrayList.get(IntOfWhateverIsSelected) (Which will always be a Ranged Weapon) to be created with the Arguments of the Mouse.getX() and Mouse.getY(). How could I possibly attempt this?
SPower SPower

2012/10/14

#
In the default constructor:
MouseInfo info = Greenfoot.getMouseInfo();
if (info == null) return;
// use the info.getX and getY methods
davmac davmac

2012/10/15

#
The best way is to have RangedWeapon implement a 'createCopy' method (with as many parameters as you like) and have that create the new instance. You can override it in each subclass of RangedWeapon to return a new instance of the correct type.
You need to login to post a reply.