C Books Guide and List
C++ Books Guide and List
Best Java Books

3,749 questions

4,049 answers

114 comments

10,705 users

How to use Dynamic Method Dispatch?

0 votes
80 views
asked May 12, 2014 by augustaina Sr Member (4,820 points)

1 Answer

0 votes
class A {
  void callme() {
    System.out.println("Inside A's callme method");
  }
}

class B extends A {
  void callme() {
    System.out.println("Inside B's callme method");
  }
}

class C extends A {
  void callme() {
    System.out.println("Inside C's callme method");
  }
}

class Dispatch {
  public static void main(String args[]) {
    A a = new A(); // object of type A
    B b = new B(); // object of type B
    C c = new C(); // object of type C
    A r; // obtain a reference of type A

    r = a; // r refers to an A object
    r.callme(); // calls A's version of callme

    r = b; // r refers to a B object
    r.callme(); // calls B's version of callme

    r = c; // r refers to a C object
    r.callme(); // calls C's version of callme
  }
}
answered May 12, 2014 by smith Geek (15,340 points)

Related questions

0 votes
1 answer 34 views
34 views asked Dec 29, 2013 by john Guru (27,140 points)
0 votes
1 answer 18 views
18 views asked Jan 26, 2014 by john Guru (27,140 points)
0 votes
1 answer 76 views
0 votes
1 answer 75 views
75 views asked May 10, 2014 by smith Geek (15,340 points)
0 votes
1 answer 77 views
77 views asked May 10, 2014 by augustaina Sr Member (4,820 points)
...