Summary: Like fields and methods, Java allows classes to be members of other classes. Here, we divide the nested classes into 4 types--Nested top-level classes (nested top-level classes), member inner classes (instance inner classes), local internal classes (locally inner Classes) and anonymous inner class (anonymous inner classes).
When I teach Java, I often find that students try to declare other methods in the method. However, unlike Pascal,--pascal allows nested declaration procedures to be procedures (similar to methods), which Java is not allowed to do. For the following code, try declaring the Innermethod () method in Outermethod (), which will pass through at compile time.
void outerMethod ()
{
void innerMethod ()
{
}
}
However, Java supports class nesting at the start of the Java language Specification 1.1, and the Java compiler allows a class to appear in another class. The following code snippet shows how to nest the Innerclass class in the Outerclass class.
class outerClass
{
class innerClass
{
}
}
Why are Java support classes nested, and what classes are nested with Java support? The following sections will answer these questions, and when you finish reading this, you will learn about nesting and use it to write powerful Java programs. First let's take a look at why Java support classes are nested.
Note: After publishing the JDK1.1, Sun publishes the documentation for the internal class specification. This document refers to the use of nested top-level classes and internal classes. After reading this article, I strongly recommend that you browse these documents.
Why are Java support classes nested?
Java does not necessarily support class nesting. In fact, if you look at the internal class specification document, you will find out where the application of the class nesting is. However, there are at least two benefits to Java support class nesting:
. Make the source code clearer
. Reduce the naming conflict