Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- A a = aa.getObject();
- if (a instanceof B) {
- B b = (B) a;
- b.do();
- }
- // ...
- public abstract class A {
- public abstract void do();
- }
- public class B extends A {
- public void do() {
- System.out.println("In B");
- }
- }
- public class Test {
- public static void main(String[] args) {
- A obj = returnA();
- obj.do(); // Will invoke class B's do() method
- }
- /** Method returning BaseClass A's reference pointing to subclass instance **/
- public static A returnA() {
- A obj = new B();
- return obj;
- }
- }
- if (obj instanceof B) {
- B obj1 = (B) obj;
- }
- public class E {
- public static void doMethod(A a) {
- Class<?> class1 = a.getClass();
- Method method;
- try {
- method = class1.getDeclaredMethod("doMethod", null);// B, C, D has doMethod
- method.invoke(a, null);
- // I know to many exceptions
- } catch (SecurityException e) {
- e.printStackTrace();
- } catch (NoSuchMethodException e) {
- e.printStackTrace();
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- e.printStackTrace();
- }
- }
- }
- A a = new B();
- public interface Doer {
- public void do();
- }
- public class B extends A implements Doer {
- //implement do method
- }
- //.. same for other subclass
Add Comment
Please, Sign In to add comment