English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Summary of Java Inner Class Usage

1. What is an inner class?63;

A class defined within a class is called an inner class

 public class Out{
   class In{ //At this time, In is an inner class
   } 
}

2. Why use inner classes?63;

1) Enhance encapsulation, hide the inner class in the outer class, and do not allow other classes to access the inner class

2) Inner classes can improve the readability and maintainability of the code

3. Classification of inner classes

For the classification of inner classes, it can be compared with the classification of member variables.

We can divide member variables according to different modifiers or different definition positions, such as: class member variables, instance member variables, local variables.

If the inner class is regarded as a member of the outer class, then the inner class can use public/default/protected/private modifier. It can also be static modifier.

Similarly, inner classes are also divided according to different modifiers or different definition positions4Class:

1) Instance inner class: inner class not using static modifier

2) Static inner class: inner class using static modifier

3) Local inner class: inner class defined in a method

4) Anonymous inner class: can be used only once, a special case of inner class

3.1Instance inner class:

1) Definition: Instance inner class, that is, inner class not using static modifier. This indicates that the instance inner class belongs to the object of the outer class, not to the outer class itself (analogous to fields).

2) Create instance inner class

//Outer class
class Outter {
 // Instance inner class: without using static modifier
 class Inner {
 }
}
public class InnerDemo1 {
 public static void main(String[] args) {
 // The instance inner class is not static, belongs to the object of the outer class, therefore, before creating an instance inner class, an object of the outer class must exist
 Outter out = new Outter();
 // Create an inner class object through an outer class object
 Outter.Inner in = out.new Inner();
 }
}

3)Characteristics:

a. From the process of creating an instance inner class, it can be known that when there is an object of the inner class, there must be an object of the outer class.

b. The instance inner class holds a reference to the instance of the outer class automatically, and the instance inner class can access all fields and methods of the outer class without any conditions

Note: When a member inner class has a member variable or method with the same name as the outer class, a hiding phenomenon occurs

c. External classes cannot directly access the members of inner classes; one must first create an object of the member inner class and then access it through a reference to that object

//Outer class
class Outter {
 private String name = "out";
 private Integer age = 17;
 // Instance inner class: without using static modifier
 class Inner {
 private Integer age = 18; // Hiding phenomenon, hiding the age of the outer class
 Inner() {
  // Characteristics:1. The instance inner class can directly access the members of the outer class
  // 2. When the instance inner class and the outer class have fields or methods with the same name, hiding occurs
  System.out.println(name + this.age);// Output out18
  // At this time, if you need to use the age of the outer class, the syntax is: outer_class.this.age
  System.out.println(Outter.this.age);// Output17
 }
 }
}

Summary: Simply put, it is to look at the scope of variables, the scope of the member variables of the outer class is the entire outer class, and the inner class is in the outer class (can be regarded as the field of the outer class), so the inner class can naturally access the outer class. And if the outer class wants to access the members of the inner class, it can be understood like this: The members of the inner class belong to the inner class and are effective within the inner class. If the inner class does not exist, the member variables within it will not exist either, so the outer class cannot directly access the members of the inner class, and must first create an object of the member inner class and then access it through the reference pointing to this object.

3.2Static inner class

1) Definition: An inner class that uses the static modifier. Therefore, this inner class belongs to the outer class itself, not to the object of the outer class

2) Create static inner class

//Outer class
class Outter {
 // Static inner class: using static modifier
 static class Inner {
 }
}
public class InnerDemo2 {
 public static void main(String[] args) {
 // Because the static inner class belongs to the outer class itself, it can be accessed directly through the class name of the outer class (like a field)
 Outter.Inner in = new Outter.Inner();
 }
}

3)Characteristics:

a. When creating an instance of the inner class, there is no need to create an instance of the outer class.

b. Static inner classes can directly access the static members of the outer class, and if you want to access the instance members of the outer class, you must access them through the instance of the outer class.

Simple understanding: Static members belong to the class, non-static members belong to the object. If you want to access the instance members (non-static members) of the outer class, of course, you must have an object of the outer class. Since the creation of a static inner class does not require an object of the outer class, if you want to access the instance members of the outer class, you must access them through the instance of the outer class.

c. Static inner classes can define static members and instance members.

d. The test class can access the static members of the static inner class directly through the full class name.

//Outer class
class Outter {
 static String name = "outter";
 public Integer age = 17;
 // Static inner class: using static modifier
 static class Inner {
 Inner() {
  // Static inner classes can directly access the static members of the outer class
  System.out.println(name);// Output outter
  // To access the instance members of the outer class, it must be accessed through an instance of the outer class.
  System.out.println(new Outter().age);// Output 17
 }
 }
}

3.3Local inner class (almost never used)

1)Definition: An inner class defined within a method, whose scope of visibility is the current method, is at the same level as local variables, so local inner classes can only be used within methods.

Note that like local variables within methods, local inner classes cannot have public, protected, private, or static modifiers.

public class InnerDemo3 {
 public static void main(String[] args) {
 // Local inner class
 class Inner {
 }
 }
}

2)Characteristics:

a. Local inner class and instance inner class cannot contain static members. (Local inner class belongs to a method, while static members belong to the class)

b. Local inner class and instance inner class can access all members of the outer class.

c. Local inner class access to local variables must be marked with final in Java8is automatically implicitly added final (syntactic sugar).

Reason: After a method is called and executed, the current method's stack frame is destroyed, and the space for local variables within the method is completely destroyed. However, the object of the inner class may still be in the heap memory, and it will only be destroyed when it is no longer referenced. In this case, there will be a situation where the inner class needs to access a non-existent local variable. To avoid this problem, we use the final modifier for local variables to make them constants, permanently resident in memory space. Even after the method is destroyed, the local variable remains in memory, and the object can continue to hold it.

public class InnerDemo3 {
 public static void main(String[] args) {
 int age = 17;
 final int num = 15;
 // Local inner class
 class Inner {
  public void test() {
  // Error: Cannot refer to a non-final variable age inside an inner class defined in a different method
  System.out.println(age);
  System.out.println(num);// Correct
  }
 }
 }
}

3.4Anonymous inner class (most frequently used)

1Definition: An anonymous inner class is a local inner class without a name, suitable for classes used only once.

2Create an anonymous inner class:

An anonymous inner class itself does not have a constructor, but will call the superclass constructor. Generally, anonymous inner classes are used to inherit from other classes or implement interfaces, and do not need to add additional methods, but only to implement or override inherited methods.

Note: An anonymous inner class must inherit from a superclass or implement an interface, but can only inherit from one superclass or implement one interface.

//Define an interface
interface Person {
 public void eat();
}
public class AnonymousDemo {
 public static void main(String[] args) {
 // Using Anonymous Inner Class
 Person p = new Person() {
  public void eat() {
  System.out.println("eat something");
  }
 };
 p.eat();
 }
}

4.Summary

5.Interview Question

public class Outer {
 public void someOuterMethod() {
 // Line 3
 }
 public class Inner {
 }
 public static void main(String[] argv) {
 Outer o = new Outer();
 // Line 8
 }
}
/*
 * Which instantiates an instance of Inner63;
A. new Inner(); // At line 3
B. new Inner(); // At line 8
C. new o.Inner(); // At line 8
D. new Outer.Inner(); // At line 8
 */

Answer A.new Inner(); is equivalent to this.new Inner(); An Outer class object already exists.

line 8 The correct way should be: o.new Inner();

This is the full content of this article. I hope the content of this article can bring a certain amount of help to everyone's learning or work, and I also hope to support the Yelling Tutorial more!

Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#w3Please replace '#' with '@' when sending an email for reporting. Provide relevant evidence, and once verified, this site will immediately delete the content suspected of infringement.