Search code examples
javaclassinterfaceanonymous

Java Anonymous Class with Interface


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)

  1. I really don't get why the method someFunction(); expects a Interface as a parameter

  2. I also don't understand why I can pass an instance of an interface to that function(inmain()). 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.


Solution

  • I'll assume public check() was a typo.

    1. 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.

    1. 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.