Java Java Data Structures Efficiency! Custom Serialization

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.

michaelcodes
michaelcodes
5,599 Points

Hi there, I am a bit confused on the anonymous class thing myself, but for the sort() method it is comparing 2 things at a time, and returning with either a negative number, 0, or a positive number. This is representing whether thing1 is greater than, less than, or equal to thing2. It repeats this process until it has sorted everything. In the case of the video thing1 and thing2 are the songs of the songbook. Hope this helped with this part of the question.

2 Answers

Boban Talevski
Boban Talevski
24,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.

Thank you both! I can now understand it much better! michaelcodes Boban Talevski

michaelcodes
michaelcodes
5,599 Points

Awesome :) , thank you also Boban that helped me out!