Guest User

Untitled

a guest
Jan 16th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. A a = aa.getObject();
  2. if (a instanceof B) {
  3. B b = (B) a;
  4. b.do();
  5. }
  6. // ...
  7.  
  8. public abstract class A {
  9. public abstract void do();
  10. }
  11.  
  12. public class B extends A {
  13. public void do() {
  14. System.out.println("In B");
  15. }
  16. }
  17.  
  18. public class Test {
  19. public static void main(String[] args) {
  20. A obj = returnA();
  21.  
  22. obj.do(); // Will invoke class B's do() method
  23. }
  24.  
  25. /** Method returning BaseClass A's reference pointing to subclass instance **/
  26. public static A returnA() {
  27. A obj = new B();
  28. return obj;
  29. }
  30. }
  31.  
  32. if (obj instanceof B) {
  33. B obj1 = (B) obj;
  34.  
  35. }
  36.  
  37. public class E {
  38.  
  39. public static void doMethod(A a) {
  40. Class<?> class1 = a.getClass();
  41. Method method;
  42. try {
  43. method = class1.getDeclaredMethod("doMethod", null);// B, C, D has doMethod
  44. method.invoke(a, null);
  45. // I know to many exceptions
  46. } catch (SecurityException e) {
  47. e.printStackTrace();
  48. } catch (NoSuchMethodException e) {
  49. e.printStackTrace();
  50. } catch (IllegalArgumentException e) {
  51. e.printStackTrace();
  52. } catch (IllegalAccessException e) {
  53. e.printStackTrace();
  54. } catch (InvocationTargetException e) {
  55. e.printStackTrace();
  56. }
  57.  
  58. }
  59. }
  60.  
  61. A a = new B();
  62.  
  63. public interface Doer {
  64. public void do();
  65. }
  66.  
  67. public class B extends A implements Doer {
  68. //implement do method
  69. }
  70.  
  71. //.. same for other subclass
Add Comment
Please, Sign In to add comment