スーパークラスのコンストラクタを使用するかどうかを選択できますか?
スーパークラスのコンストラクターの 1 つを独自のオブジェクトを構築する前に呼び出す必要があるため、スーパークラスのコンストラクターを使用するかどうかを条件付きで制御することはできません。
上記から、Java には、コンストラクターの最初の行でスーパークラスのコンストラクターを呼び出す必要があるという要件があります。実際、スーパークラスのコンストラクターへの明示的な呼び出しがなくても、暗黙的な呼び出しが行われます。に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.
// ...
}
}
他の何かを実行した後にスーパークラスのコンストラクターを呼び出すことはできないことに注意してください。
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.
}
}
代替手段
つまり、ここで必要なことを達成する方法は、何らかの条件に応じて実装の種類を選択できるファクトリ メソッド patternを使用することです。
public A getInstance() {
if (condition) {
return new B();
} else {
return new C();
}
}
上記のコードでは、 に応じて、メソッドはまたはcondition
のインスタンスを返すことができます(両方が class のサブクラスであると仮定します)。B
C
A
例
interface
以下は、ではなくを使用した具体的な例class
です。
次のインターフェイスとクラスがあるとします。
interface ActionPerformable {
public void action();
}
class ActionPerformerA implements ActionPerformable {
public void action() {
// do something...
}
}
class ActionPerformerB implements ActionPerformable {
public void action() {
// do something else...
}
}
次に、メソッドを介して渡される条件に応じて、上記のクラスのいずれかを返すクラスがあります。
class ActionPeformerFactory {
// Returns a class which implements the ActionPerformable interface.
public ActionPeformable getInstance(boolean condition) {
if (condition) {
return new ActionPerformerA();
} else {
return new ActionPerformerB();
}
}
}
次に、条件に応じて適切な実装を返す上記のファクトリ メソッドを使用するクラス:
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();
}
}