Definition: A local class is declared within the body of a method, constructor, or another block of code. It's not associated with any enclosing class.
Access: Local classes have access to all the local variables and parameters of the enclosing method or block of code, provided they are declared final or effectively final.
Visibility: Local classes have the same visibility (e.g., private, protected, default, public) as the enclosing method or block of code.
When to use: Local classes are useful when you need a class that is only used for a specific purpose within a particular method or block of code.
Example:
```java
public class OuterClass {
private int outerField;
public void someMethod() {
// Local class inside a method
class LocalClass {
public void accessOuterField() {
System.out.println(outerField); // Can access outer class's private field
}
}
// Create an instance of the local class
LocalClass localClassInstance = new LocalClass();
// Access the local class's method
localClassInstance.accessOuterField();
}
}
```
Nested Class:
Definition: A nested class is declared within the body of another class, but outside the body of any method or block of code.
Access: Nested classes have access to the private members (fields and methods) of the enclosing class.
Visibility: Nested classes can be declared with different visibility modifiers (e.g., private, protected, default, public).
When to use: Nested classes are useful when you want to group related classes together or when you need a class that closely interacts with the enclosing class.
Example:
```java
public class OuterClass {
private int outerField;
public class NestedClass {
public void accessOuterField() {
System.out.println(outerField); // Can access outer class's private field
}
}
public void someMethod() {
// Create an instance of the nested class
NestedClass nestedClassInstance = new NestedClass();
// Access the nested class's method
nestedClassInstance.accessOuterField();
}
}
```
A nested class differs from a local class in terms of accessibility, the ability to access private members of the enclosing class, and the scope in which they are declared. Local classes have a narrower scope and visibility compared to nested classes.