Running on Java 17+35-2724 (Preview)
Home of The JavaSpecialists' Newsletter

3.17 Anonymous Inner Classes

Juppies 2 by Dr Heinz M. Kabutz

Instead of declaring the class OriginalScrambler, we can also define it as an anonymous inner class (also called anonymous type). It is anonymous because it doesn't really have a name. Our previous class was called OriginalScrambler, now it is called something like ScrambledWordLibrary$1.

The anonymous type (or anonymous inner class) has the same name as the interface that we want to implement, in our case "Scrambler", and then we have an open curly brace { after the constructor call Scrambler(). We then add the method scramble() and close the anonymous type with a closing curly brace } and a semicolon ;

We do this for the OriginalScrambler, the RandomScrambler and the SortedScrambler. We will leave the Rot13Scrambler as it is, it will be clear in the next section why we do that.

Since the classes are private to the class, we are allowed to change them at will to anonymous types and back, without letting anyone know what we have done. Users of this class would use the Scramblers that we have declared inside the ScrambledWordLibrary as constants.

Comments

When you load these comments, you'll be connected to Disqus. Privacy Statement.

Table of Contents

We hope you enjoyed this tutorial. If you did, you will also enjoy our courses. We suggest you start with Extreme Java - Advanced Java, followed by Extreme Java - Concurrency Performance for Java 8.



About the Author

Heinz Kabutz Java Conference Speaker

Java Champion, author of the Javaspecialists Newsletter, conference speaking regular... About Heinz

Superpack 21

Superpack 21 Our entire Java Specialists Training in one huge bundle more...

Free Java Course

Free Juppies 2 Course
Juppies 2 - a course for complete beginners more...

Free Java Book

Dynamic Proxies in Java Book
Java Training

We deliver relevant courses, by top Java developers to produce more resourceful and efficient programmers within their organisations.

Java Consulting

We can help make your Java application run faster and trouble-shoot concurrency and performance bugs...

Java Emergency?

If your system is down, we will review it for 15 minutes and give you our findings for just 1 € without any obligation.