Java: Superclass to construct a subclass on certain conditions, possible?
- by ramihope
I have this condition
public class A {
public action() {
System.out.println("Action done in A");
}
}
public class B extends A {
public action() {
System.out.println("Action done in B");
}
}
when I create an instance of B, the action will do just actions in B, as it overrides the action of the superclass.
the problem is that in my project, the super class A is already used too many times, and I am looking for a way that under certain conditions, when i create an instance of A it makes a check and if it is true, replace itself with B.
public class A {
public A() {
if ([condition]) {
this = new B();
}
}
public action() {
System.out.println("Action done in A");
}
}
A a = new A();
a.action();
// expect to see "Action done in B"...
is this possible in some way?