Java: Superclass to construct a subclass on certain conditions, possible?

Posted by ramihope on Stack Overflow See other posts from Stack Overflow or by ramihope
Published on 2010-05-05T12:44:58Z Indexed on 2010/05/05 12:48 UTC
Read the original article Hit count: 142

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about java

Related posts about superclass