杰瑞科技汇

Java内部类如何高效使用?

Of course! The phrase "Java in the inner" is a bit ambiguous, but it most likely refers to one of two fundamental concepts in Java:

Java内部类如何高效使用?-图1
(图片来源网络,侵删)
  1. Inner Classes: Classes defined inside another class.
  2. Inner Loops: Loops defined inside the body of another loop.

Let's break down both, as they are both very common and important in Java programming.


Inner Classes (Classes within Classes)

An inner class is a class that is defined inside another class. The "outer" class is often called the enclosing class or outer class.

Inner classes are used to logically group classes that are only used in one place. This promotes better encapsulation and can make your code more readable and maintainable.

There are four types of inner classes in Java:

Java内部类如何高效使用?-图2
(图片来源网络,侵删)

a) Member Inner Class

This is the most common type. It's defined as a member of the outer class, just like a field or a method.

Key Characteristics:

  • It has access to all members (fields and methods) of the outer class, including private ones.
  • The outer class can access all members of the inner class, including private ones.

Example:

class OuterClass {
    private String outerField = "I am from the Outer Class";
    // Member Inner Class
    class InnerClass {
        public void display() {
            // Inner class can access private members of the outer class
            System.out.println("Accessing from Inner: " + outerField);
        }
    }
    // Method of the outer class that creates and uses the inner class
    public void useInnerClass() {
        InnerClass inner = new InnerClass();
        inner.display();
    }
}
// How to use it
public class Main {
    public static void main(String[] args) {
        OuterClass outer = new OuterClass();
        outer.useInnerClass(); // Output: Accessing from Inner: I am from the Outer Class
        // You can also instantiate it directly from outside
        OuterClass.InnerClass innerInstance = outer.new InnerClass();
        innerInstance.display();
    }
}

b) Static Nested Class

This is a special type of inner class. It's declared with the static keyword.

Java内部类如何高效使用?-图3
(图片来源网络,侵删)

Key Characteristics:

  • It's not an inner class in the strictest sense because it doesn't have a "link" to an instance of the outer class.
  • It cannot access non-static members (fields or methods) of the outer class. It can only access static members.
  • You instantiate it using the outer class name: OuterClass.StaticNestedClass.

Example:

class OuterClass {
    private String outerField = "Instance field";
    private static String staticOuterField = "Static field";
    // Static Nested Class
    static class StaticNestedClass {
        public void display() {
            // This will cause a COMPILE ERROR because it's trying to access a non-static member
            // System.out.println(outerField); 
            // This works fine
            System.out.println("Accessing from Static Nested: " + staticOuterField);
        }
    }
}
// How to use it
public class Main {
    public static void main(String[] args) {
        // Note: No instance of OuterClass is needed
        OuterClass.StaticNestedClass nested = new OuterClass.StaticNestedClass();
        nested.display(); // Output: Accessing from Static Nested: Static field
    }
}

c) Local Inner Class

This class is defined inside a method of the outer class.

Key Characteristics:

  • It's only visible within the method where it's defined.
  • It can access final or effectively final local variables of the enclosing method.

Example:

class OuterClass {
    private String outerField = "Outer field";
    public void methodWithLocalClass() {
        String localVariable = "Local variable";
        // Local Inner Class
        class LocalInnerClass {
            public void display() {
                System.out.println("Accessing from Local Inner: " + outerField);
                System.out.println("Accessing local variable: " + localVariable);
            }
        }
        // You can only create and use it inside this method
        LocalInnerClass local = new LocalInnerClass();
        local.display();
    }
}
// How to use it
public class Main {
    public static void main(String[] args) {
        OuterClass outer = new OuterClass();
        outer.methodWithLocalClass(); 
        /* Output:
           Accessing from Local Inner: Outer field
           Accessing local variable: Local variable
        */
    }
}

d) Anonymous Inner Class

This is a local inner class that has no name. It's a "shorthand" for creating a class that implements an interface or extends a class on the fly.

Key Characteristics:

  • It's defined and instantiated in a single expression.
  • It's often used for event handlers, thread creation, or providing a simple implementation of an interface.

Example:

// An interface
interface Greeting {
    void sayHello();
}
// How to use it
public class Main {
    public static void main(String[] args) {
        // Creating an instance of an anonymous class that implements Greeting
        Greeting greeting = new Greeting() {
            @Override
            public void sayHello() {
                System.out.println("Hello from an anonymous inner class!");
            }
        };
        greeting.sayHello(); // Output: Hello from an anonymous inner class!
    }
}

Note: In modern Java (8+), this is often replaced by Lambda Expressions for functional interfaces, which is more concise:

// Modern equivalent using a lambda
Greeting greeting = () -> System.out.println("Hello from a lambda!");
greeting.sayHello();

Inner Loops (Loops within Loops)

This refers to the concept of nesting one loop inside another. This is extremely useful for iterating over multi-dimensional data structures like 2D arrays (matrices) or for performing complex operations that require repeating a repetitive task.

Common Use Case: Processing a 2D array.

Example: Imagine you have a 2D array representing a grid:

1  2  3
4  5  6
7  8  9

To print every element, you need an outer loop to go through each row and an inner loop to go through each column in that row.

public class Main {
    public static void main(String[] args) {
        // A 2D array (a matrix)
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };
        System.out.println("Printing the matrix using nested loops:");
        // Outer loop iterates through the rows
        for (int i = 0; i < matrix.length; i++) {
            // Inner loop iterates through the columns of the current row
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            // Print a new line after each row is complete
            System.out.println();
        }
    }
}

Output:

Printing the matrix using nested loops:
1 2 3 
4 5 6 
7 8 9 

How break and continue Work with Inner Loops

When you use break or continue inside an inner loop, it only affects the innermost loop it is in.

Example:

public class Main {
    public static void main(String[] args) {
        outerLoop:
        for (int i = 1; i <= 3; i++) {
            System.out.println("\nOuter loop iteration: " + i);
            for (int j = 1; j <= 3; j++) {
                if (i == 2 && j == 2) {
                    System.out.println("  -> Breaking out of the inner loop.");
                    break; // This only breaks the inner 'j' loop
                }
                System.out.println("  Inner loop: " + j);
            }
        }
    }
}

Output:

Outer loop iteration: 1
  Inner loop: 1
  Inner loop: 2
  Inner loop: 3
Outer loop iteration: 2
  Inner loop: 1
  -> Breaking out of the inner loop.
Outer loop iteration: 3
  Inner loop: 1
  Inner loop: 2
  Inner loop: 3

To break out of both loops, you can use a labeled break.

Example with Labeled Break:

public class Main {
    public static void main(String[] args) {
        outerLoop: // This is a label
        for (int i = 1; i <= 3; i++) {
            System.out.println("\nOuter loop iteration: " + i);
            for (int j = 1; j <= 3; j++) {
                if (i == 2 && j == 2) {
                    System.out.println("  -> Breaking out of BOTH loops.");
                    break outerLoop; // This breaks the loop labeled 'outerLoop'
                }
                System.out.println("  Inner loop: " + j);
            }
        }
    }
}

Output:

Outer loop iteration: 1
  Inner loop: 1
  Inner loop: 2
  Inner loop: 3
Outer loop iteration: 2
  Inner loop: 1
  -> Breaking out of BOTH loops.

Summary

Concept "Java in the inner" Refers To Purpose Key Feature
Inner Classes A class defined inside another class. To logically group related classes and increase encapsulation. Has access to the outer class's members (depending on type).
Inner Loops A loop defined inside another loop. To iterate over multi-dimensional data or perform repetitive repetitive tasks. break/continue affect only the innermost loop unless using a label.
分享:
扫描分享到社交APP
上一篇
下一篇