Junior
What are nested classes?
sobes.tech AI
Answer from AI
Nested classes are classes declared within another class. They can be static (static nested classes) or non-static (inner classes).
Static nested classes:
- Declared with the
staticmodifier. - Do not have direct access to non-static members of the outer class (only through an instance of the outer class).
- Can contain both static and non-static members.
- Are created without an instance of the outer class.
public class Outer {
private static int staticOuterVar = 10;
private int instanceOuterVar = 20;
public static class StaticNested {
// Has access to staticOuterVar
public void printStaticValue() {
System.out.println(staticOuterVar);
}
// Does not have direct access to instanceOuterVar
// public void printInstanceValue() {
// System.out.println(instanceOuterVar); // Compilation error
// }
}
}
Using a static nested class:
// Example of creating an instance of a static nested class
Outer.StaticNested nestedObject = new Outer.StaticNested();
nestedObject.printStaticValue(); // Will print 10
Non-static nested classes (Inner Classes):
- Declared without the
staticmodifier. - Have full access to all members of the outer class, including private members.
- Cannot contain static members (except compile-time constants).
- Require an instance of the outer class to be created.
public class Outer {
private static int staticOuterVar = 10;
private int instanceOuterVar = 20;
public class Inner {
// Has access to staticOuterVar and instanceOuterVar
public void printValues() {
System.out.println(staticOuterVar); // Accessible
System.out.println(instanceOuterVar); // Accessible
}
}
}
Using a non-static nested class:
// Example of creating an instance of a non-static nested class
Outer outerObject = new Outer();
Outer.Inner innerObject = outerObject.new Inner();
innerObject.printValues(); // Will print 10 and 20
Advantages of using nested classes:
- Logical grouping: Classes used only by one other class can be logically grouped inside it.
- Encapsulation: Nested classes have access to private members of the outer class.
- Readability and maintainability: Code becomes more organized.
Types of non-static nested classes:
- Local classes: Declared within a method.
- Anonymous classes: Classes without a name, typically used to create an instance of an abstract class, interface, or base class with method overrides.
Local class:
public class Outer {
public void myMethod() {
class LocalClass {
void display() {
System.out.println("Inside local class");
}
}
LocalClass local = new LocalClass();
local.display();
}
}
Anonymous class (example with interface):
interface Greeting {
void sayHello();
}
public class Outer {
public void greet() {
Greeting anonymousGreeting = new Greeting() {
@Override
public void sayHello() {
System.out.println("Hello from anonymous class!");
}
};
anonymousGreeting.sayHello();
}
}