It is possible to choose whether or not to use a superclass' constructor?
It is not possible to conditionally control whether or not to use a superclass' constructor, as one of the superclass' constructors must be called before constructing one's own object.
From the above, there is a requirement in Java, that the first line of the constructor must call on of the superclass' constructor -- in fact, even if there is no explicit call to a superclass' constructor, there will be an implicit call to super()
:
public class X {
public X() {
// ...
}
public X(int i) {
// ...
}
}
public class Y extends X {
public Y() {
// Even if not written, there is actually a call to super() here.
// ...
}
}
It should be stressed that it is not possible to call the superclass' constructor after performing something else:
public class Y extends X {
public Y() {
doSomething(); // Not allowed! A compiler error will occur.
super(); // This *must* be the first line in this constructor.
}
}
The alternative
That said, a way to achieve what is desired here could be to use the factory method pattern, which can select the kind of implementation depending on some kind of condition:
public A getInstance() {
if (condition) {
return new B();
} else {
return new C();
}
}
In the above code, depending on condition
, the method can return either an instance of B
or C
(assuming both are a subclass of class A
).
Example
The following is a concrete example, using an interface
rather than a class
.
Let there be the following interfaces and classes:
interface ActionPerformable {
public void action();
}
class ActionPerformerA implements ActionPerformable {
public void action() {
// do something...
}
}
class ActionPerformerB implements ActionPerformable {
public void action() {
// do something else...
}
}
Then, there would be a class which will return one of the above classes depending on a condition which is passed in through a method:
class ActionPeformerFactory {
// Returns a class which implements the ActionPerformable interface.
public ActionPeformable getInstance(boolean condition) {
if (condition) {
return new ActionPerformerA();
} else {
return new ActionPerformerB();
}
}
}
Then, a class which uses the above factory method which returns the appropriate implementation depending on a condition:
class Main {
public static void main(String[] args) {
// Factory implementation will return ActionPerformerA
ActionPerformable ap = ActionPerformerFactory.getInstance(true);
// Invokes the action() method of ActionPerformable obtained from Factory.
ap.action();
}
}