Java nested classes and inner classes

  • 2020-04-01 03:51:58
  • OfStack

What are nested classes and inner classes?

      You can define another class within one class, called nested classes, which come in two types:
Static nested classes and non-static nested classes. Static nested classes are rarely used, and the most important are non-static nested classes, which are called as
Inner class. Nested classes were introduced starting with JDK1.1. The inner class can be divided into three types:

      First, an inner class directly defined in a class (external class);
      An inner class defined in a method (a method of an outer class);
      Third, anonymous inner class.

Next, I'll explain the use and considerations of these nested classes.

Static nested classes

      To define a static nested class,


public class StaticTest {
private static String name = "javaJohn";
private String id = "X001"; static class Person{
private String address = "swjtu,chenDu,China";
public String mail = "josserchai@yahoo.com";//Internal class public member
public void display(){
//System.out.println(id);// Non-static members of an external class cannot be accessed directly
System.out.println(name);//Only static members of external classes can be accessed directly
System.out.println("Inner "+address);//Access this inner class member. < br / > }
} public void printInfo(){
Person person = new Person();
person.display(); //System.out.println(mail);// inaccessible
//System.out.println(address);// inaccessible System.out.println(person.address);//You can access the private member of the inner class
System.out.println(person.mail);//Public members of internal classes can be accessed }
public static void main(String[] args) {
StaticTest staticTest = new StaticTest();
staticTest.printInfo();
}
}

Inside static nested classes, non-static members of external classes cannot be accessed, as defined by the Java syntax "static methods cannot access non-static members directly."
If you want to access the variables of an external class, you must do it in other ways, and for this reason, static nested classes are rarely used. Note that the external class accesses inside
The members of a subclass are somewhat special and cannot be accessed directly, but can be accessed via an inner class, because all members and methods statically nested default to
Static. Also note that the internal static class Person is only visible within the scope of the class StaticTest, and it is an error to refer to or initialize it in another class.

Define inner classes in outer classes

      The following code defines two inner classes and their calling relationships in the outer class:


public class Outer{
int outer_x = 100; class Inner{
public int y = 10;
private int z = 9;
int m = 5;
public void display(){
System.out.println("display outer_x:"+ outer_x);
}
private void display2(){
System.out.println("display outer_x:"+ outer_x);
} } void test(){
Inner inner = new Inner();
inner.display();
inner.display2();
//System.out.println("Inner y:" + y);// Cannot access internal internal variables
System.out.println("Inner y:" + inner.y);//You can access
System.out.println("Inner z:" + inner.z);//You can access
System.out.println("Inner m:" + inner.m);//You can visit InnerTwo innerTwo = new InnerTwo();
innerTwo.show();
} class InnerTwo{
Inner innerx = new Inner();
public void show(){
//System.out.println(y);// inaccessible Innter the y Members of the
//System.out.println(Inner.y);// Not directly accessible Inner Any member and method
innerx.display();//You can access
innerx.display2();//You can access
System.out.println(innerx.y);//You can access
System.out.println(innerx.z);//You can access
System.out.println(innerx.m);//You can access
}
} public static void main(String args[]){
Outer outer = new Outer();
outer.test();
}
}

The above code needs to be stated that, for inner classes, the class keyword of the class is usually defined without a public or private qualifier, if so
There is no effect, and it seems that these qualifiers have no effect on the variables and methods of the inner class (?). . Also, notice the Inner classes Inner and Inner
InnterTwo is only known within the scope of class Outer, and if any code outside of class Outer attempts to initialize or use the class Inner, compilation does not
Will pass. At the same time, the variable members of the inner class are only visible within the inner part. If the outer class or the inner class of the same level need access, the sample program should be used
Method in which you cannot directly access the variables of an inner class.

Define inner classes in methods
      The following code defines an inner class inside a method:

Public class FunOuter {
Int out_x = 100;

Public void test () {
The class Inner {
String x = "x";
Void the display () {
System. The out. Println (out_x);
}
}
Inner Inner = new Inner();
Inner. The display ();
}

Public void showStr (String STR) {
//public String str1 = "test Inner"; // is not definable and only final modifications are allowed
//static String str4 = "static Str"; // is not definable and only final modifications are allowed
String str2 = "test Inner";
Final String str3 = "final Str";
The class InnerTwo {
Public void testPrint () {
System. The out. Println (out_x); // directly access variables of external classes
/ / System. Out. Println (STR); // non-final variables inside this method cannot be accessed
/ / System. Out. Println (str2); // non-final variables inside this method cannot be accessed
System. The out. Println (str3); // only the final variable members of this method can be accessed
}
}
InnerTwo InnerTwo = new InnerTwo();
InnerTwo. TestPrint ();
}

Public void the use () {
//Inner innerObj = new Inner(); // now the Inner is no longer visible.
/ / System. Out. Println (Inner. X); // now the Inner is no longer visible.
}


Public static void main(String[] args) {
FunOuter = new FunOuter();
The (outer);
}
}


From the above routine we can see that the inner class defined inside the method has less visibility, it is only inside the method
As you can see, the outer class (and other methods of the outer class) are no longer visible. At the same time, it has a feature, is the method
The inner class is not even accessible to the member variables of the method, it can only access the final members of the method. And the other one
It is important to note that the method defines a member internally, allowing only final or no modifiers, and nothing else such as static is available.

5. Anonymous inner class
      The code below defines an anonymous inner class: anonymous inner classes are commonly used for event handling in Java


import java.applet.*;
import java.awt.event.*;     public class AnonymousInnerClassDemo extends Applet{
    public void init(){
        addMouseListener(new MouseAdapter(){
            public void mousePressed(MouseEvent me){
             showStatus("Mouse Pressed!");
        }
        })
    }
    public void showStatus(String str){
        System.out.println(str);
    }
    }

In the above example, the method addMouseListener accepts an object-type parameter expression, so in the parameter, we define an anonymous inner class that is a MouseAdapter type class, and in the class we define an inherited method mousePressed, the whole class as an argument. The class has no name, but it is automatically instantiated when the expression is executed. Also, because the anonymous inner class is defined inside the AnonymousInnerClassDemo class, it can access its method showStatus. This is consistent with the previous inner class.

Other problems with the use of inner classes

From the above, we can clearly see some usage of inner classes, and, in many cases, inner classes are used in event handling, such as Java, or as value objects. At the same time, we need to pay attention to the final problem, which is that the inner class is defined just like any other class, and it can also inherit classes from other packages and implement interfaces elsewhere. It can also inherit from other inner classes at the same level, or even from external classes themselves. Let's end with a final example:


public class Layer {
//The member variable of the Layer class
private String testStr = "testStr"; //Person class, base class
class Person{
String name;
Email email;
public void setName(String nameStr){
this.name = nameStr;
}
public String getName(){
return this.name;
}
public void setEmail(Email emailObj){ this.email = emailObj;
}
public String getEmail(){
return this.email.getMailStr();
}
//Inner class of inner class, multilayer inner class
class Email{
String mailID;
String mailNetAddress;
Email(String mailId,String mailNetAddress){
this.mailID = mailId;
this.mailNetAddress = mailNetAddress;
}
String getMailStr(){
return this.mailID +"@"+this.mailNetAddress;
}
}
}
//Another inner class inherits the outer class itself
class ChildLayer extends Layer{
void print(){
System.out.println(super.testStr);//Access to the parent class's member variable
}
}
//Another inner class inherits the inner class Person
class OfficePerson extends Person{
void show(){
System.out.println(name);
System.out.println(getEmail());
}
}
//Test method of external class
public void testFunction(){
//Test the first inner class
ChildLayer childLayer = new ChildLayer();
childLayer.print(); //Test the second inner class
OfficePerson officePerson = new OfficePerson();
officePerson.setName("abner chai");
//Notice that you have to use object. New to subclass the object
//Instead of person.new Email(...) < br / > //New person. Email(...) < br / > officePerson.setEmail(officePerson.new Email("josserchai","yahoo.com")); officePerson.show();
}
public static void main(String[] args) {
Layer layer = new Layer();
layer.testFunction();
}
}


Related articles: