aspose file tools*
The moose likes Java in General and the fly likes which method is called? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Reply locked New topic
Author

which method is called?

ramchander yshetti
Ranch Hand

Joined: Apr 22, 2006
Posts: 97
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

Joined: Aug 25, 2003
Posts: 227

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

Joined: Dec 27, 2005
Posts: 1249

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

Joined: Mar 06, 2001
Posts: 13459

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: which method is called?