Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Test
- {
- public static void main(String[] args)
- {
- abc a = new abc();
- dog b = new dog();
- cat d = new cat();
- animal c = a.mno(b);
- animal w = a.mno(d);
- }
- }
- abstract class animal
- {
- public abstract void move ();
- public void move2 () {
- System.out.println("Animal moving");
- }
- }
- class dog extends animal
- {
- public void bark()
- {
- System.out.println("ruff");
- }
- @Override
- public void move() {
- System.out.println("Dog moving");
- }
- }
- class cat extends animal
- {
- public void bark()
- {
- System.out.println("meow");
- }
- @Override
- public void move() {
- System.out.println("Cat moving");
- }
- }
- class abc
- {
- public animal mno(animal a) {
- // a.bark();
- // causes error because parent Animal has
- // no idea of bark in child classes
- /*
- * One way to think about variables would be to think of them as pointers to Objects. Here a reference of Animal(parent class)
- * 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
- * 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.
- * 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
- * has implemented(overridden) the method being invoked.
- *
- * Think of it as INVOKING THE METHOD IN THE OBJECT THE REFERENCE POINTS TO
- * and not INVOKING THE METHOD IN THE REFERENCE ITSELF.
- */
- a.move();
- // every object inherits the definition from the parent class.
- a.move2();
- return a;
- }
- }
- /*
- * OUTPUT:
- * Dog moving
- * Animal moving
- * Cat moving
- * Animal moving
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement