Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Dynamic dispatch

 
suavedeep kaur
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As it is said that if a superclass contains a method that is overridden by a subclass,then when different types of objects are reffered to through a superclass reference variable ,different versions of the method are executed .

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

}

class B extends A{
void callme(){

System.out.println(" in b's callme method ");
}

}


class C extends B {

void callme(){
System.out.println("in C's callme method ");
}

}


class Dispatch{
public static void main(String args[]){

A a = new A();
a.callme();
B b =new B();
b.callme();
C c=new C();
c.callme();

A ob =new B();
ob.callme();
ob= c;
ob.callme();
}
}


outputs
in A's callme method
in b's callme method
in C's callme method
in b's callme method
in C's callme method


what i am not getting is if the above statement is as true then i can access b's callme method with class B's reference variable only why??? please clarify me this ,though i understand the above statement but how come the b's callme method and c's callme method got executed without there superclass reference . please help me
 
Sagar Rohankar
Ranch Hand
Posts: 2907
1
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
though i understand the above statement but how come the b's callme method and c's callme method got executed without there super class reference . please help me


Thats not necessary, when you create B`s or C`s object , and assigned them to there respective class reference , there is no problem .

The reference varible 'b' and 'c' , are referring to "B" and "C"`s object , and they have 'callme()' method, that`s why they are executing it.



There is no polymorphic calls here, they are straightforward method execution !
 
Amit Ghorpade
Bartender
Posts: 2854
10
Fedora Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi suavedeep kaur ,
please UseCodeTags.
Your code is unreadable, so you wont get good replies.

Hope this helps
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic