Java內(nèi)部類(lèi)(Inner Class)是定義在另一個(gè)類(lèi)中的類(lèi)。它們可以簡(jiǎn)化代碼,提高代碼的可讀性和可維護(hù)性。以下是一些使用Java內(nèi)部類(lèi)簡(jiǎn)化代碼的方法:
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內(nèi)部類(lèi)可以幫助我們簡(jiǎn)化代碼,提高代碼的可讀性和可維護(hù)性。在實(shí)際開(kāi)發(fā)中,我們可以根據(jù)需求選擇合適的內(nèi)部類(lèi)類(lèi)型來(lái)優(yōu)化代碼結(jié)構(gòu)。