Junior — Middle
Is an inner class in Java private to access from other classes?
sobes.tech AI
Answer from AI
An inner class in Java is not necessarily inaccessible from other classes. Access depends on the access modifier assigned to it (private, protected, public, or package-private). For example, if an inner class is declared as private, it is only accessible within the outer class. If declared as public or with no modifier (package-private), it can be accessed from other classes in the same package or through import.
Example:
public class Outer {
private class InnerPrivate {}
public class InnerPublic {}
}
// From another class in the same package:
Outer.InnerPublic obj = new Outer().new InnerPublic(); // allowed
// Outer.InnerPrivate obj2 = new Outer().new InnerPrivate(); // compile error