Reputation: 37
I didn't write Java for a long time and need some help with something (maybe) simple.
So I got this Class
in which an Interface
is declared :
public class test(){
interface Checker(){
public check();
}
public someFunction(List param1, Checker param2){
//[do something here]
}
...
public static void main (...){
someFunction(List param1, new Checker(){
...
//[implementation of interface]
...
});
}
So my problem is, that (and the actual Code works fine)
I really don't get why the method someFunction();
expects a Interface
as a parameter
I also don't understand why I can pass an instance of an interface to that function(in
main()). The second argument that I'm passing the
someFunction();`, is an instance of an interface, right?
Well, what i was thinking of, is that it actually is some kind of anonymous class and therefore it might be possible.
But as I said, it's been a while since I wrote java code, and I didn't find an answer yet, so I would be really grateful if somebody could explain to me why and how this piece of code is working.
Upvotes: 0
Views: 3460
Reputation: 88707
- i really dont get, WHY the method someFunction() expects a Interface as parameter
That's a choice of the developer but using an interface here allows you to use any implementation - and only interfaces allow a sort of muliple inheritance in Java.
- i also dont understand WHY i can pass an instance of an interface to that function (in main()). The second argument that i'm passing the someFunction(), is an instance of an interface, right? Well, what i was thinking of, is that it actually is some kind of anonymous Class and therefore it might be possible.
The code you see basically creates an anonymous implementation of the interface and instance of that anonymous class. So your guess is correct here.
Upvotes: 1
Reputation: 3915
I'll assume public check() was a typo.
- i really dont get, WHY the method someFunction() expects a Interface as parameter
Why not? Your interface is Checker
and your method signature is
public someFunction(List param1, Checker param2)
The second argument takes a Checker
.
- i also dont understand WHY i can pass an instance of an interface to that function (in main()).
You aren't passing an instance of an interface. You are passing an anonymous class. When you say:
new Checker(){
...
//[implementation of interface]
...
});
you are implementing the interface.
Upvotes: 0
Reputation: 609
1) Because by definition public someFunction(List param1, Checker param2)
expects an object of Checker (see parameter 2)
2) Yes, it is an anonymous class, and an instance of it new Checker()
creates an object of the class which is passed.
Hence, the code works.
Upvotes: 1