amit
amit

Reputation: 10892

Can Java Constructor construct an object of a subclass?

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?

Upvotes: 4

Views: 1803

Answers (5)

Pavel Minaev
Pavel Minaev

Reputation: 101605

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 they do new A(), they get an object of class A, and no other.

Upvotes: 9

akf
akf

Reputation: 39495

No, constructors will only to instantiate an object of the class they represent. That is why there is no return value specified in the constructor.

Upvotes: 5

Tadeusz Kopec for Ukraine
Tadeusz Kopec for Ukraine

Reputation: 12413

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.

Upvotes: 3

Andreas
Andreas

Reputation: 5335

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 {

}

Upvotes: 4

trshiv
trshiv

Reputation: 2505

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.

Upvotes: 1

Related Questions