jeudi 18 août 2016

How to return a subclass object when receive object is base class (Java)

I have following situation and would like to know the best way to design my solution

public abstract class A {
  public abstract A getHelper();
  public abstract void launchHandle();  
  public static A initHelper(String condition) throws Exception {
      if ( condition == 'xyz') {
         return C.getHelper();
      } else {
          return B.getHelper();
      }
  }
}

public class B extends A {
  protected static A b;

  @Override
  public A getHelper() {
    b = new B();
    return b;
  }

 @Override
  public void launchHandle() {
   System.out.println("Launching Handle");
  }

  public String getName() {
   return "I am from Class B";
  }
}

public class C extends A {
  protected static A c;

  @Override
  public A getHelper() {
    c = new C();
    return c;
  }

 @Override
  public void launchHandle() {
   System.out.println("Launching Handle from C");
  }

  public String getValue() {
   return "I am from Class C";
  }
}

**Executor class**

public class Executor {

  public static void main(String[] args) {
      A aa = a.initHelper(condition);
   }
}

Now in the above approach, i am unable to access methods like aa.getName() from Class B OR aa.getValue() from Class C, which makes sense. However how to get these methods in executor class? Executor does not know anything about Class B & C and should not know. Executor is only aware of Class A, but want to access methods SubClass methods from B & C which are extended from Class A.

Please help design this and what could be best way to solve this.

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire