My problem is that I have a class, which needs to extend either one of two classes - the one it should extend depends on some value that is determined during runtime.

I understand that there isn't a concept of having an if (this condition) extend thisclass else extend thisclass
but the same effect needs to be achieved.

How can this be done?

5 Years
Discussion Span
Last Post by stultuske

eh? you can't extend more then one class directly, besides: extending a class is in the (compiled) code, so you can't do that "on the fly".
what you could do (I guess) is something like this:

interface MyMarker{}

public class MyFirstClass extends Parent1 implements MyMarker{


public class MySecClass extends Parent2 implements MyMarker{


public class Bus{

public static void main(String[] args){
  MyMarker obj;
  if ( args[0].equals("Parent1")
    obj = new MyFirstClass();
  else if ( args[0].equals("Parent2")
    obj = new MySecClass();

and keep the methods that both should have in the MyMarker interface, to avoid problems
not saying this is the only (nor the best, for that matter) sollution, but it's one way to think.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.