#javaDay29
Geeks With Geeks Geeks With Geeks
548 subscribers
1 view
0

 Published On Jun 7, 2024

In Java, an inner class is a class that is defined within another class. Inner classes have access to the members (including private members) of the outer class. They can be used to logically group classes that are only used in one place, enhance encapsulation, and can lead to more readable and maintainable code. There are several types of inner classes in Java:

1. Member Inner Class
A member inner class is a non-static class that is defined inside another class. It is associated with an instance of the enclosing class and can access its members.

#### Example:
```java
class OuterClass {
private String outerField = "Outer Field";

class InnerClass {
void display() {
System.out.println("Outer field is: " + outerField);
}
}
}

public class Main {
public static void main(String[] args) {
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.display(); // Output: Outer field is: Outer Field
}
}
```

2. Static Nested Class
A static nested class is a static class that is defined inside another class. It does not have access to the instance members of the outer class. It can access the static members of the outer class.

#### Example:
```java
class OuterClass {
private static String outerStaticField = "Outer Static Field";

static class StaticNestedClass {
void display() {
System.out.println("Outer static field is: " + outerStaticField);
}
}
}

public class Main {
public static void main(String[] args) {
OuterClass.StaticNestedClass nested = new OuterClass.StaticNestedClass();
nested.display(); // Output: Outer static field is: Outer Static Field
}
}
```

3. Local Inner Class
A local inner class is a class defined within a method, constructor, or block. It can only be accessed within the scope where it is defined.

#### Example:
```java
class OuterClass {
void display() {
class LocalInnerClass {
void printMessage() {
System.out.println("This is a local inner class.");
}
}

LocalInnerClass localInner = new LocalInnerClass();
localInner.printMessage(); // Output: This is a local inner class.
}
}

public class Main {
public static void main(String[] args) {
OuterClass outer = new OuterClass();
outer.display();
}
}
```

4. Anonymous Inner Class
An anonymous inner class is an inner class without a name and for which only a single object is created. They are used to override methods of a class or an interface.

#### Example:
```java
interface Greeting {
void sayHello();
}

public class Main {
public static void main(String[] args) {
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!
}
}
```

show more

Share/Embed