Junior — Middle
What is the purpose of inner classes in object-oriented programming?
sobes.tech AI
Answer from AI
Inner classes in object-oriented programming are used for logical grouping of classes that are closely related and do not make sense outside the context of the outer class. They help improve encapsulation, as the inner class can access the private members of the outer class.
For example, in Android, inner classes are often used to implement event listeners or auxiliary components that are closely related to the outer class and should not be used separately.
Example in Java:
public class Outer {
private int outerValue = 10;
class Inner {
void printOuterValue() {
System.out.println("Outer value: " + outerValue); // access to the private field of the outer class
}
}
}