Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2017
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. public class Test
  2. {
  3. public static void main(String[] args)
  4. {
  5. abc a = new abc();
  6. dog b = new dog();
  7. cat d = new cat();
  8. animal c = a.mno(b);
  9. animal w = a.mno(d);
  10. }
  11. }
  12.  
  13. abstract class animal
  14. {
  15. public abstract void move ();
  16. public void move2 () {
  17. System.out.println("Animal moving");
  18.  
  19. }
  20. }
  21. class dog extends animal
  22. {
  23. public void bark()
  24. {
  25. System.out.println("ruff");
  26. }
  27.  
  28. @Override
  29. public void move() {
  30. System.out.println("Dog moving");
  31. }
  32. }
  33.  
  34. class cat extends animal
  35. {
  36. public void bark()
  37. {
  38. System.out.println("meow");
  39. }
  40.  
  41. @Override
  42. public void move() {
  43. System.out.println("Cat moving");
  44. }
  45. }
  46.  
  47. class abc
  48. {
  49. public animal mno(animal a) {
  50. // a.bark();
  51. // causes error because parent Animal has
  52. // no idea of bark in child classes
  53.  
  54. /*
  55. * One way to think about variables would be to think of them as pointers to Objects. Here a reference of Animal(parent class)
  56. * can refer to an object of Cat / Dog (child class). The only restriction is that you can only invoke those methods on the reference that
  57. * are in the parent class. When a method is invoked, the reference merely invokes the method of the same name in the object it points to.
  58. * So the reference pointer doesn't need to distinguish between Dog/Cat object so long as the object is a child of the reference type and
  59. * has implemented(overridden) the method being invoked.
  60. *
  61. * Think of it as INVOKING THE METHOD IN THE OBJECT THE REFERENCE POINTS TO
  62. * and not INVOKING THE METHOD IN THE REFERENCE ITSELF.
  63. */
  64. a.move();
  65.  
  66. // every object inherits the definition from the parent class.
  67. a.move2();
  68. return a;
  69. }
  70. }
  71. /*
  72. * OUTPUT:
  73. * Dog moving
  74. * Animal moving
  75. * Cat moving
  76. * Animal moving
  77. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement