Java polymorphism creating new subclass object using superclass variable
I want to create a new instance depending on an object where I have a superclass variable. Is this possible without implementing the getNew () function, or without using the 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();
}
source to share
After some time for reflection and input from zv3dh, I have solved this second answer.
Now I am getting a new instance of a subclass SuperClass instance without knowing the specific subtype at runtime.
For this you have a "reflection".
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 are looking for "java reflexion" you will get many results here on SO and on the web.
source to share
Take a look at the "FactoryMethod" design pattern.
This is exactly what you are looking for: it encapsulates a "new" operator.
However, your example makes me wonder:
- Your getNew () is echoing what the constructor will do anyway
Try something like this:
public abstract class SuperClass {
public SuperClass createSuperClass(object someParam) {
if (someParem == a) return new SubClassA();
if (someParem == b) return new SubClassB();
}
}
public class SubClassA extends SuperClass {
}
public class SubClassB extends SuperClass {
}
As you can see, you need some IF in some place ...
source to share