[JavaSE Column 65] The use of internal classes, classes defined inside other classes

Author homepage : Designer Xiao Zheng
Author brief introduction : 3 years of JAVA full-stack development experience, focusing on JAVA technology, system customization, remote guidance, dedicated to enterprise digital transformation, certified lecturer of CSDN College and Blue Bridge Cloud Course.
Main direction : Vue, SpringBoot, WeChat applet

This article explains the concept and syntax of inner classes in Java, and gives sample codes. An inner class is a class defined inside another class. The inner class can access the members of the outer class, and can play the role of hiding and encapsulation.

insert image description here


1. What is an inner class

Inner classes in Java are classes defined inside other classes .

The inner class can access the members of the outer class (including private members), and can play the role of hiding and encapsulation.

The following is a sample code of a simple Java inner class, please copy and execute it locally.

public class OuterClass {
    
    
    private int outerVariable = 10;

    public void outerMethod() {
    
    
        InnerClass innerObj = new InnerClass();
        innerObj.innerMethod();
    }

    public class InnerClass {
    
    
        private int innerVariable = 5;

        public void innerMethod() {
    
    
            System.out.println("Inner Variable: " + innerVariable);
            System.out.println("Outer Variable: " + outerVariable);
        }
    }

    public static void main(String[] args) {
    
    
        OuterClass outerObj = new OuterClass();
        outerObj.outerMethod();
    }
}

In this example, OuterClassan inner class is included InnerClass.

InnerClassOuterClassMember variables of the external class can be directly accessed outerVariable, and methods can be called OuterClassby creating an instance of .InnerClassinnerMethod()

In main()the method, we create a OuterClassobject and call outerMethod()the method, which in turn creates a InnerClassobject and call innerMethod()the method. In innerMethod()the method, we print out the member variables of the inner class innerVariableand the member variables of the outer class outerVariable.

This example shows how inner classes can access members of outer classes and how to create and use instances of inner classes.

The inner class is divided into the following 4 44 types, please study carefully.

  1. Member inner class : defined inside the class, and has the same member level as the outer class. Members of an inner class can access all members of the outer class, including private members. When creating an instance of a member's inner class, an instance of the outer class must first be created.
  2. Static inner class : staticThe inner class decorated with keywords has nothing to do with the instance of the outer class and can be directly accessed through the outer class. A static inner class cannot access non-static members of the outer class, only static members of the outer class.
  3. Method inner class : A class defined inside a method can only be used within the scope of the method. The method inner class can access the members of the outer class (including method parameters and local variables), but can only access the finalmodified local variables.
  4. Anonymous inner class : An inner class without a name, used to create a class that only needs to be used once. Anonymous inner classes are usually used when creating interface objects or inheriting parent classes.

The characteristics of the inner class include the following 4 4At 4 o'clock, please study hard.

  • Inner classes can access members of outer classes , including private members.
  • An inner class can be hidden in an outer class and not visible to other classes of the outer class.
  • Inner classes can implement multiple inheritance , and a class can inherit multiple inner classes at the same time.
  • Inner classes can access instances of outer classes , including instance variables and instance methods.

The usage scenarios of inner classes include the following 3 3At 3 o'clock, please study hard.

  • Encapsulation : Make the inner class private for use only by the outer class.
  • Code Organization : Organize related classes together to improve code readability and maintainability.
  • Callback mechanism : Internal classes can implement interfaces or inherit abstract classes for the implementation of callback methods.

In short, an inner class is a special class that can access members of an outer class and is used to implement functions such as encapsulation, code organization, and callbacks.

insert image description here


2. What is the difference between inner class and ordinary class

Inner classes and ordinary classes in Java have the following 6 6There are 6 differences, please study carefully.

  1. Access rights : Inner classes can access private members of outer classes, while ordinary classes cannot directly access private members of outer classes. This is because the inner class is a member of the outer class and can enjoy all the access rights of the members of the outer class.
  2. Association : There is an association between the inner class and the outer class, and the inner class can access members of the outer class, including instance variables and methods. There is no such special association between ordinary classes.
  3. Creation method : The instance of the inner class must depend on the instance of the outer class. You need to create an instance of the outer class first, and then create an instance of the inner class. Ordinary classes can directly newcreate instances through keywords.
  4. Type : Inner classes can be divided into member inner classes, static inner classes, method inner classes, and anonymous inner classes. Whereas a normal class has only one type.
  5. Hiddenness : Inner classes can be hidden in outer classes and are not visible to other classes in outer classes. Ordinary classes do not have this kind of concealment, and are visible to other classes outside the class.
  6. Usage scenarios : Internal classes are usually used for special requirements scenarios such as encapsulation, code organization, and implementation of callback mechanisms. Ordinary classes are better suited for general object-oriented programming.

In short, the differences between internal classes and ordinary classes are mainly reflected in access rights, associations, creation methods, types, concealment, and usage scenarios. Students can choose appropriate class types to implement functions according to specific needs. .

insert image description here


3. Application scenarios of internal classes

Inner classes have many application scenarios in Java, the following are some common 6 66 application scenarios.

  1. Implement the callback mechanism : the inner class can implement the interface or inherit the abstract class for the implementation of the callback method. Implementing the callback mechanism through the inner class can simplify the writing of the code, making the code clearer and more maintainable.
  2. Encapsulation and hiding : Inner classes can be privately modified, hidden in outer classes, and only accessible inside the outer class. This enables encapsulation and prevents classes other than the outer class from directly accessing the inner class.
  3. Optimize code structure : Internal classes can organize related classes together to improve code readability and maintainability. By defining the inner class where it needs to be used, the number of classes can be reduced and the code structure can be simplified.
  4. Realize multiple inheritance : Internal classes can realize multiple inheritance, and a class can inherit multiple internal classes at the same time. This can avoid the restriction that Java does not support multiple inheritance, and realize more flexible class relationships.
  5. Access to the private members of the outer class : The inner class can access the private members of the outer class, including private variables and private methods. In this way, the access and operation of the private members of the external class can be realized, and the function of the internal class is enhanced.
  6. Anonymous Inner Class : An inner class can be used to create a class that only needs to be used once, that is, an anonymous inner class. Through the anonymous inner class, you can quickly define the relevant implementation logic and simplify the code when creating an interface object or inheriting a parent class.

insert image description here


4. Internal class interview questions

  1. What are the types of inner classes in Java? Describe the differences and usage scenarios between them respectively.
  2. Can an inner class access private members of an outer class? Why?
  3. How can I create an instance of an inner class somewhere other than the outer class?
  4. What is the difference between a static inner class and a non-static inner class?
  5. Why can an anonymous inner class access the local variables of the outer class without declaring it final?
  6. How to access member variables and methods of static inner class and non-static inner class?
  7. Can an inner class have its own inner class?
  8. What is the scope of inner classes?
  9. How to create instance of inner class in outer class?
  10. What are the similarities and differences between inner classes and inheritance relationships?

V. Summary

This article explains the concept and syntax of internal classes in Java, and gives sample codes. In the next blog, I will explain the instanceofknowledge points of Java keywords and data type conversion.

insert image description here

Guess you like

Origin blog.csdn.net/qq_41464123/article/details/132075408