tags:

views:

149

answers:

6

Is there a way to modify the class being constructed in a constructor?

public class A {
  A() {
    //if (condition) return object of type B
    //else return A itself
  }
}
public class B extends A { }

Basically I want to use the base class constructor as a factory method. Is it possible in java?

+2  A: 

No, you can't do this.

Noon Silk
+5  A: 

No, constructors will only allow a return value of the class they represent. That is why there is no return value specified in the constructor.

akf
Constructors don't return values
Steve Kuo
+8  A: 

No, you'll have to use a factory method for A if you want to do this. The client of your class has a right to expect that, if he does new A(), he gets an object of class A, and no other.

Pavel Minaev
well, this is possible in some other languages. when user does new A() he can as well get subtype of A. So conceptually I see no issue.
Nonetheless, it is the expectation in Java.
Pavel Minaev
+1  A: 

You could try using reflection to instantiate the subclass. However it is a bad idea because a class shouldn't know about its subclasses.

Using a factory method is the best approach in your case.

trshiv
+1  A: 

You cannot do it in a constructor but you could do:

public class A {

private A(){ }

public static A getInstance(){
     if (condition) 
        return new B();
     else 
        return new A();
}

}

class B extends A {

}
andreas
+1  A: 

When constructor code is being invoked the object is already created - you are only initializing its fields. So it's too late to modify class of the object.

Tadeusz Kopec