Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Make a new object of a returned class in java

I have an ArrayList of a class, Monster, and inside the ArrayList is different subclasses of Monster, like Slime or Zombie. I then use a method to return a random class from that ArrayList. What I need to know is how to make a new object of the type that is returned. Right now I have a "reset" method for each subclass that basically reconstructs the object, but I don’t want to have to make a reset method for every subclass.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

As long as you don’t have a lot of types of monsters, you can do something like this:

interface Monster {}
class Zombie implements Monster {}
class Slime implements Monster {}

private static Monster duplicateMonster(Monster monster) {
    if (monster.getClass() == Zombie.class) {
        return new Zombie();
    } else if (monster.getClass() == Slime.class) {
        return new Slime();
    }
    throw new Exception("Unknown Monster");
}

Monster anotherMonster = duplicateMonster(someMonster);

Another way would be to have a method in each class that makes a new instance of that same class. Like this:

interface Monster {
    Monster makeNewOne();
}
class Zombie implements Monster {
    public Monster makeNewOne() {
        return new Zombie();
    }
}
class Slime implements Monster {
    public Monster makeNewOne() {
        return new Slime();
    }
}

Monster anotherMonster = someMonster.makeNewOne();

You could implement a typical copy() method that would work just like above, but it would take each of the attributes of the monster you’re calling the method on and transfer those to the new Monster, thereby making a copy that looks the same.

It is possible using introspection to get the class of an object and then ask for that class’s constructor and then call that to create a new object. But that’s kinda messy.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading