Java内部类(Inner Class)是定义在另一个类中的类。它们可以简化代码,提高代码的可读性和可维护性。以下是一些使用Java内部类简化代码的方法:
public class OuterClass {
private int data = 10;
class InnerClass {
void display() {
System.out.println("Data from outer class: " + data);
}
}
public static void main(String[] args) {
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.display();
}
}
public class OuterClass {
class InnerClass implements Comparable<Integer> {
int data;
@Override
public int compareTo(Integer o) {
return Integer.compare(data, o);
}
}
public static void main(String[] args) {
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.data = 5;
System.out.println("Comparison result: " + inner.compareTo(10));
}
}
public class OuterClass {
void createInnerClass() {
final int data = 10;
class InnerClass {
void display() {
System.out.println("Data from outer class: " + data);
}
}
OuterClass.InnerClass inner = new InnerClass();
inner.display();
}
public static void main(String[] args) {
OuterClass outer = new OuterClass();
outer.createInnerClass();
}
}
public class OuterClass {
interface MyInterface {
void doSomething();
}
public static void main(String[] args) {
OuterClass outer = new OuterClass();
MyInterface myInterface = () -> System.out.println("Hello from anonymous inner class!");
myInterface.doSomething();
}
}
总之,Java内部类可以帮助我们简化代码,提高代码的可读性和可维护性。在实际开发中,我们可以根据需求选择合适的内部类类型来优化代码结构。