Through previous studies, we already know that a class can have two important members: member variables and methods . In fact, a class also has one kind of member: an inner class. When a class defines another class, we call such a class an inner class , and the class containing the inner class is called an outer class of the inner class.
1) The member variables of the outer class of the inner class are still valid in the inner class, and the methods in the inner class can also call the methods in the outer class.
2) Class variables and class methods cannot be declared in the class body of an inner class. In the class body of an outer class, an inner class can be used to declare objects as members of an outer class.
3) An inner class can only be used by its outer nested classes. Other classes cannot use the inner class of a certain class to declare objects.
Because the member variables of the outer class of the inner class are valid in the inner class, the interaction between the inner class and the outer class is very convenient.
For example:
classRedCowForm{staticStringformName;RedCowcow;//Internal class declaration object RedCowForm(){}RedCowForm(Strings){cow=newRedCow(88,66,2000);formName=s;}publicvoidshowCowMess(){cow.speak();}classRedCow {//Inner class declaration StringcowName=calf;intheight,weight,price;RedCow(inth,intw,intp){height=h;weight=w;price=p;}voidspeak(){System.out.println( I am +cowName+, height+height+cm, weight+weight+kg, living in +formName);}}}publicclassMain{publicstaticvoidmain(String[]args){RedCowFormform=newRedCowForm(dotcpp farm);form.showCowMess(); form.cow.speak();}}
The running results are as follows:
I am a calf. I am 88cm tall and weigh 66kg. I live on a dotcpp farm. I am a calf. I am 88cm tall and weigh 66kg. I live on a dotcpp farm.
Note : The name of the bytecode file of the internal class generated by the Java compiler is different from the name of the ordinary class. The name format of the bytecode file corresponding to the internal class is " embedded class name $ internal class name ". For example: the name of the bytecode file of the internal class in the above example should be RedCowForm$RedCow.class.
Inner classes can be modified as static inner classes. Static inner classes are a static data type in embedded classes. Programs can use static inner classes in other classes to create objects. However, static inner classes cannot operate in embedded classes. instance member variables.
Okay, everyone can experiment on the computer and digest and absorb the content of this section.