Bookmark Topic Watch Topic
  • New Topic

which method is called?

 
ramchander yshetti
Ranch Hand
Posts: 97
  • Mark post as helpful
  • send pies
  • Report post to moderator
interface A {
int add(int a,int b);
}
abstract class B {
abstract int add(int a, int b);
}

public class C extends B implements A {
public int add(int a, int b) {
return a+b;
}
public static void main(String args[]) {
C c12=new C();
c12.add(5,7);//which method is called i.e interface or abstract
}
}
 
Aditya Jha
Ranch Hand
Posts: 227
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Report post to moderator
Hi Ramchander,

Technically, the method which gets called is neither of interface A nor of class B, rather it is of class C.

Theoritically, you can consider a method call to be associated with the reference it is associated with. However, at run time, method call is decided based on the actual class of instance the reference is pointing to.

In your example, it is the reference of class C (c12) which is calling the method add(). Hence it is the method of class C which gets called (if you prefer to say so). Had it been , we might say that it is the method of interface A which gets called. Similarily, for calling method of class B, we could have written .

Please note, that no matter which version you use, ultimately it is the method of class C which gets executed. This is evident even in case of method add() not being abstract in class B.

Regards,

- Aditya
 
Shaan Shar
Ranch Hand
Posts: 1249
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Report post to moderator
What's this Duplicate Thread


Which Method is Called...

Sheriffs and Bartenders Pls close this thread.

yathamshetti ramchander Don't do like this.. wait for the replies in a single thread.

Why are you creating duplicate threads... for the same topic...
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Report post to moderator
Agreed, please don't post the same question in multiple forums, it creates duplicate conversations and wastes the time of the people trying to help you.

Dave.
 
    Bookmark Topic Watch Topic
  • New Topic