I want to create a new instance depending on an object, where I have the super class variable. Is this somehow possible without implementing a getNew() function or without usage of an ugly if chain? In other words: How to implement the following newSubClass(..) function without using the getNew() function?
public abstract class SuperClass {
abstract public SuperClass getNew();
}
public class SubClassA extends SuperClass {
@Override
public SuperClass getNew() {
return new SubClassA();
}
}
public class SubClassB extends SuperClass {
@Override
public SuperClass getNew() {
return new SubClassB();
}
}
private SuperClass newSubClass(SuperClass superClass) {
return superClass.getNew();
}
After having some time to think about and zv3dh's contribution I decided this second answer.
I'am getting now you want an new instance of an instance of a subclass' type of SuperClass without knowing the concrete sub-type at runtime.
For that you have "reflexion".
public abstract class A_SuperClass {
public A_SuperClass createNewFromSubclassType(A_SuperClass toCreateNewFrom) {
A_SuperClass result = null;
if (toCreateNewFrom != null) {
result = toCreateNewFrom.getClass().newInstance();
}
// just an example, add try .. catch and further detailed checks
return result;
}
}
public class SubClassA extends A_SuperClass {
}
public class SubClassB extends A_SuperClass {
}
If you search for "java reflexion" you will get lots of results here on SO and on the web.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With