Java内部类(Inner Class)是定义在另一个类(外部类)内部的类。它们可以提高封装性,主要体现在以下几个方面:
public class OuterClass {
private int secret = 42;
class InnerClass {
public void revealSecret() {
System.out.println("The secret is: " + secret);
}
}
}
public class OuterClass {
protected int secret = 42;
class InnerClass {
public void revealSecret() {
System.out.println("The secret is: " + secret);
}
}
}
public class OuterClass {
class InnerClass implements InterfaceA, InterfaceB {
// Implement methods of InterfaceA and InterfaceB
}
}
public class OuterClass {
private boolean isAdmin = false;
class AdminInnerClass extends InnerClass {
public void performAdminTasks() {
// Admin-specific tasks
}
}
class RegularInnerClass extends InnerClass {
public void performRegularTasks() {
// Regular user tasks
}
}
InnerClass createInnerClass() {
if (isAdmin) {
return new AdminInnerClass();
} else {
return new RegularInnerClass();
}
}
}
总之,Java内部类可以通过隐藏实现细节、控制访问权限、实现多重继承和提供灵活的封装等方式来提高封装性。