0
class Vertebrates {
  public void move() {
    System.out.println("Move");
  }
}
class Mammel extends Vertebrates {
  public void move() {
    System.out.println("Walk");
  }
}
class Dog extends Mammel{
  public void move() {
    System.out.println("Walk on haws");
  }
}
class Demo {
  public static void main(String args[]) {
    Dog d = new Dog();
    //insert code here
  }
}

How can I call the move() method of Vertebrate by using the reference d of type Dog, using super statement or something?

Mat
  • 202,337
  • 40
  • 393
  • 406
JDN
  • 1
  • 2
  • possible duplicate of [In Java, how do I call a base class's method from the overriding method in a derived class?](http://stackoverflow.com/questions/268929/in-java-how-do-i-call-a-base-classs-method-from-the-overriding-method-in-a-der) – Joe Feb 08 '15 at 12:58
  • possible duplicate of [Why is super.super.method(); not allowed in Java?](http://stackoverflow.com/questions/586363/why-is-super-super-method-not-allowed-in-java) – Kenster Feb 08 '15 at 14:02
  • Dog can call `super.move()` to access Mammal's `move()`. Dog can't get directly to Vertebrates' `move()`. – Kenster Feb 08 '15 at 14:04

2 Answers2

0

You should not do that! There is a reason why we have OOP and encapsulation! This kind of problem is usually a design problem. You should reconsider your choices and ask yourself if the methods should be implemented differently.

(There is still a way:

class Dog extends Mammel{
  public void move() {
    System.out.println("Walk on haws");
    try {
     this.getClass()
         .getSuperclass()
         .getSuperclass()
         .getMethod("move", new Class[]{} )
         .invoke(  this.getClass().getSuperclass().getSuperclass().newInstance() ,new Object[]{}  );
    } catch (IllegalAccessException | InvocationTargetException | InstantiationException | NoSuchMethodException e) {
        e.printStackTrace();
    }
  }
}
class HelloWorld {
  public static void main(String args[]) {
    Dog d = new Dog();
    d.move();
    //insert code here
  }
}

prints: Walk on haws Move

Note: This is not how you should use java. There may be some highly specific edge cases where this is needed, but these are very rare. )

Leander
  • 1,322
  • 4
  • 16
  • 31
0

You can try this

  ((Vertebrates )d).move();
Saimir
  • 210
  • 2
  • 12