The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.
SeeDev.java for updated tutorials taking advantage of the latest releases.
SeeJava Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.
SeeJDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.
As mentioned in the sectionNested Classes, nested classes enable you to logically group classesthat are only used in one place, increase the use ofencapsulation, and create more readable and maintainable code.Local classes, anonymous classes, and lambda expressions alsoimpart these advantages; however, they are intended to be usedfor more specific situations:
Local class: Use it if you need to create more than oneinstance of a class, access its constructor, or introduce a new, namedtype (because, for example, you need to invoke additional methodslater).
Anonymous class: Use it if you need to declare fields or additional methods.
Use it if you are encapsulating a single unit of behavior that you want to pass to other code. For example, you would use a lambda expression if you want a certain action performed on each element of a collection, when a process is completed, or when a process encounters an error.
Use it if you need a simple instance of a functional interface and none of the preceding criteria apply (for example, you do not need a constructor, a named type, fields, or additional methods).
Nested class: Use it if your requirements are similar to thoseof a local class, you want to make the type more widelyavailable, and you don't require access to local variables ormethod parameters.
Use a non-static nested class (or inner class) if you require access to an enclosing instance's non-public fields and methods. Use a static nested class if you don't require this access.
About Oracle |Contact Us |Legal Notices |Terms of Use |Your Privacy Rights
Copyright © 1995, 2024 Oracle and/or its affiliates. All rights reserved.