Forums Register Login
Calling a method on an interface instance

I have a query due to which I am stuck. Kindly help me someone.

I have an interface having a method declaration say 'login()'.
Now in my java class where I am NOT implementing the interface, I call the method login() using the interface instance.
Now there are other 2 classes(say one.java & two.java) both implementing this interface, both having their own login() methods. Now my query is, which of the login methods with execute with the method call on the interface instance?

thanks & regards,
There's really no such thing as an "interface instance". What does exist is an instance of a class that implements the interface - an object, in other words. The method being called will be the one of whichever object you're using that implements the interface. Which leads to the question: how (or from where) are you getting the object that implements the interface?

Posting a short code excerpt that shows how you go about that would be helpful for us to understand where you're stuck.
Thanks Ulf,

I guess I could make out which method will be executed. It would be the method of the class, that instanciates the class which calls the method in the interface using the object of the interface.

I think I have written a confusing sentence. But I hope you will know what I mean.

if you have this (in pseudo-code):

in class three, if you call interfaceOne.login(), you will get the login method defined in the one class. Similarly, interfaceTwo.login() will call the method defined in the two class.

did that make sense? it doesn't matter what the REFERENCE type is, but only what the underlying OBJECT is.
Well, thats pretty obvious. I wouldnt have asked this query if it was that straight. But this is not exactly what my query was.
It was:

Suppose I have,

Now which login() will be called? The one in "class one" or the one in "class two".
I havent made up this code. I have seen this happening in the source of a working application.

[ April 22, 2008: Message edited by: shalaka wadekar ]
The answer is "neither", because the code you showed will throw a NullPointerException. Before you can invoke methods on "myint", you need to assign an object to it, and that can either be a "one" or a "two". So there's no uncertainty about which method will be called.
Thanks a lot.


This thread has been viewed 638 times.

All times above are in ranch (not your local) time.
The current ranch time is
Dec 15, 2018 04:52:35.