Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Old School

What is the "new anonymous class" said at 4min 27seconds of the video?

Instructor said "Making a brand new anonymous class from this interface & overriding the 1 abstract method that needed be completed (the compare method)". What exactly is this anonymous class, and which line is it at? Thank you

1 Answer

From the code in Main.java, the anonymous class is the one created with "new Comparator<Book>()". It's anonymous because you never store the class in a local property, it's just passed into the sort method. See example below that makes an non anonymous class The Comparator interface has an abstract method compare which this code is overriding.

// anonymous example
Collections.sort(books, new Comparator<Book>() {
            @Override
            public int compare(Book b1, Book b2) {
                return b1.getTitle().compareTo(b2.getTitle());
            }
        });

// not anonymous example
Comparator myComparator = new Comparator<Book>() {
            @Override
            public int compare(Book b1, Book b2) {
                return b1.getTitle().compareTo(b2.getTitle());
            }
        }

Java docs: https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html