Anonymous classes and interfaces
Hello, in the video : "custom serialization" Craig used an interface as an anonymous class. How does that work? Am I implementing the interface or creating an instance of the interface? I Think the second option is not even possible... Help please, thank you in advance as always. And how does that sort() works? I am not understanding its parameters.
Boban Talevski24,771 Points
Regarding the other part of the question "Am I implementing the interface or creating an instance of the interface?". You are correct, the second option isn't possible, so it's the first one. You are creating a class which implements that interface, but your class doesn't have a name. Because you only need it only right then and there and you are instantiating only a single object of it (since you use the new keyword) and passing that object as a parameter to the sort method. The object doesn't have a name as well. I know it looks weird the first time you see this.
Technically, it's the same thing as creating a separate class MyComparator.java which implements the Comparator interface inside which you would implement the compare method the same way as Craig does in the video. Then you would create a new object of that class in SongBook.java, pass it as a parameter to the sort method, and it will work the same way.
In other words, the sort method requires an object of a class which implements the Comparator interface. It doesn't care whether you have defined a separate class in a separate java file from which you'll create a new object and pass that, or just define the needed class at that point and create an object of it right there with the new keyword.
Hope it makes a bit more sense now.
And also something to keep in mind as you progress further through the Java courses. If you think about it, the sort method is actually requiring another method as a parameter, isn't it? There's this thing called a lambda expression that will make the code cleaner and accomplish the same thing...but let this sink in first.