Chapter:Interfaces - Creating an anonymous class

From Juneday education
Jump to: navigation, search

Meta information about this chapter

Expand using link to the right to see the full content.


Background about this chapter topics...


Make the student familiar with stuff brought up in this chapter...


After this chapter, the student shall understand:

  • this
  • that
  • those
  • them
  • and the reset

Instructions to the teacher

Common problems

TODO! Students often ask about X and have problems with Y...

Interfaces: Creating an anonymous class

For interfaces which declare only one or a few methods, it is actually common to create an object of a class implementing the interface "on the fly" without bothering to create a class declaration with a class name etc.

Let's say that we want to create a Comparator<String> for comparing two String objects without caring about the case of the text. We want to be able to compare two String objects as if they were both only lower case, for instance. So, we'd like to be able to compare e.g. "ABBA" with "abba" and get 0 (equality), or "ABBA" with "baba" and get a negative number, because disregarding the case "abba" is less than "baba".

We'll just need to create a class which implements Comparator<String> and override the compare(String, String) method to reflect this behavior.

The thing we could do here is to skip the step of actually defining such a class in a source code file with a class name and all. We could instead actually use the syntax for creating a nameless (anonymous) class. With this syntax we create an object and define its type in one long statement. In order to do this, we use the following syntax:

new InterfaceName(){
    // code for the method

This syntax also works for creating anonymous classes which uses inheritance. The following would create a new Object of a type which extends Object and overrides toString():

Object o = new Object(){
  public String toString(){
    return "We are anonymous. Fear us.";
System.out.println(o); // would print the text returned from toString above

So, going back to our String comparator which doesn't care about case. This code would sort a list of Strings without regard for the case of the Strings in the list:

import java.util.Comparator;
import java.util.ArrayList;
import java.util.Collections;
public class TestAnonymous{
  public static void main(String[] args){
    ArrayList<String> strings = new ArrayList<>();
    System.out.println("Unsorted: ");
    Collections.sort(strings, new Comparator<String>(){
        public int compare(String first, String other){
          return first.toLowerCase().compareTo(other.toLowerCase());
    System.out.println("Sorted disregarding case:");
    System.out.println("Sorted using String's default compareTo:");

A test run of the program would print:

$ javac && java TestAnonymous
[CEPA, bepa, APA, ABBA, DEPA, Baba]
Sorted disregarding case:
[ABBA, APA, Baba, bepa, CEPA, DEPA]
Sorted using String's default compareTo:
[ABBA, APA, Baba, CEPA, DEPA, bepa]

Chapters on the topic of Interfaces

You can check your progress on this chapter using this list:

See also

  • Java:Language_-_Streams_and_Lambdas - Lambda expressions allow you to express an implementing class even more concisely than using an anonymous class (works for functional interfaces - those who declare one single abstract method) - This is extra reading for the curious students.

Lecture slides and Videos


Further reading

Where to go next

Next page has exercises (if any) for this chapter: Interfaces_-_Creating_an_anonymous_class_-_Exercises

« PreviousBook TOCNext »