Sitemap

Inner Class in JAVA

2 min readMar 31, 2024

--

A class defined inside another class is known as an inner class in Java. Members (fields and methods) of the outer class, including private members, are accessible to inner classes.

1.Static Nested Class

Declaration:- static class InnerClassName{}

Characteristics: Treated as top-level class (Nested inside another class)

“treated as a top-level class (Nested inside another class),” it means that the class is defined within another class (the outer class) as a nested class. This nested class can be either a static nested class or an inner class (non-static nested class).

Get BansodThomas’s stories in your inbox

Join Medium for free to get updates from this writer.

example:

class Outer {
static class Nested {
void display() {
System.out.println("Nested class");
}
}
}

example:

public class OuterClass {
public static class InnerClass{
public static String message="Inner class";

public static void main(String[] args) {
InnerClass inner =new InnerClass();
System.out.println(inner.message);
}
}

private static String message="Outer Class";

public static void main(String[] args) {
OuterClass outerClass=new OuterClass();
System.out.println(outerClass.message);
InnerClass innerClass=new InnerClass();
System.out.println(innerClass.message);
}
}

Inner Class can be instantiated without an instance of the OuterClass using “new OuterClass.InnerClass Name()”.

Inner class has access to static member of the OuterClass.

Inner class cannot access non-static member of the outer class directly;(This is because an instance of a non-static inner class is implicitly associated with an instance of the outer class, so it needs an instance of the outer class to exist before it can be instantiated.)

However you can access non-static members of the outer class by using an instance of the outer class within the inner class.

example:-

public class OuterClass {
private String outerMessage = "Outer Message";

public class InnerClass {
public void displayOuterMessage() {
System.out.println(outerMessage); // Accessing outerMessage via instance of OuterClass
}
}

public static void main(String[] args) {
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.displayOuterMessage();
}
}

--

--