1

I am searching for a solution to my problem for a while now but I cannot find an answer which is specific for my question. I have a Class A which is abstract and Class B and C which extends class A. A and B are concrete classes. Class A implements function which will be inherited by V and C. Inside this function I want to create new object of B or C - the problem is that I don't know which object is that.

How can I achieve this?

public void colision(List<Organism> organisms) {

    List<Organism> temp = new ArrayList<Organism>(organisms);
    temp.remove(this);

    for (Organizm organism : temp){
        if (this.location == organizm.getLocation()){
            if (this.getClass().equals(organism.getClass())){ 
                        //here is what I need to figure out
            }
            else{ 
                ...
                }
            }
        }
    }
}
2
  • 1
    Please explain in words how you decide which class you want. Commented May 10, 2015 at 15:45
  • 3
    Add an abstract method createNewInstance() to A, and implement it in B and C. But you should really tell us what you're trying to achieve, at a higher level, because this.getClass().equals(organism.getClass())is a design smell. Commented May 10, 2015 at 15:45

3 Answers 3

5

Use Class<T>.newInstance() e.g.: organism.getClass().newInstance(). In order to do that you need to have default constructor in your class definition otherwise you need to find constructor - e.g.: Constructor constructor = organism.getClass().getDeclaredConstructor(parameterTypes...); and then use it like constructor.newInstance(arguments...);.

Sign up to request clarification or add additional context in comments.

1 Comment

Use organism.getClass().getConstructor().newInstance() for more informative exceptions.
0

Use the Factory design pattern

Comments

0

Probably you can have an abstract method getInstance() in A and then have both B and C implement that method

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.