I have several abstract classes that each have several subclasses. I want to create instances of each subclass without having to copy/paste essentially the same code for what could be literally hundreds of lines, since the number of subclasses is increasing as the program becomes more complex.
For each given abstract superclass, the subclass instances will be contained in a Map
(specifically a HashMap
). The classes (super and sub) all have constructors without parameters.
I saw answers to this question from a decade ago saying this is not possible (or, at the very least, not advisable). I'm hoping that has changed, but I've been unable to find more recent answers.
EDIT: Since apparently my question isn't clear enough, here's an example of code (emphasis on example; this is neither a MWE nor the code that I actually have):
public abstract class A {
public abstract void setName(String s);
public abstract String getName();
}
public class B extends A {
private String name = "B";
public String getName() {
return name;
}
public void setName(String s) {
name = s;
}
}
public class C extends A {
private int count = 0;
private String name = "C";
public void increaseCount() {
count++;
}
public String getName() {
return name;
}
public void setName(String s) {
name = s;
}
}
public class Base {
private Map<String, A> list;
public Base() {
list = new HashMap<>();
A b = new B();
list.put(b.getName(), b);
A c = new C();
list.put(c.getName(), c);
}
}
public class Phone {
private Map<String, A> list;
public Phone() {
list = new HashMap<>();
A b = new B();
list.put(b.getName(), b);
A c = new C();
list.put(c.getName(), c);
}
}
I would like to avoid what you see there in the constructors for Base
and Phone
. Rather than having to create a new instance every single time and then add it "by hand", which will take a ridiculous amount of time and effort, I'd prefer to use an automated way to do this, if one exists.
I didn't quite get your question, but as far as I understand it, you want to load all subclasses of any given parent class. To achieve that you can use reflection. However, you might want to review your design first, maybe you don't even need that.
Java Reflection allows to manipulate java classes (create instances, call methods, access fields, ...) at runtime.
Here is an example of someone trying to find how to load subclasses of a given class: