在Java中,内部类是定义在另一个类中的类。内部类可以访问其外部类的所有成员(包括私有成员),并且可以访问外部类的实例。内部类分为四种类型:成员内部类、局部内部类、匿名内部类和静态内部类。下面是如何在Java中使用内部类的示例:
- 成员内部类:
public class OuterClass { private int data = https://www.yisu.com/ask/10;"Accessing outer class member: " + data); } } public static void main(String[] args) { OuterClass outer = new OuterClass(); OuterClass.InnerClass inner = outer.new InnerClass(); inner.accessOuterMembers(); // 输出:Accessing outer class member: 10 } }
- 局部内部类:
public class OuterClass { public void createLocalInnerClass() { class LocalInnerClass { public void display() { System.out.println("Local inner class"); } } LocalInnerClass localInner = new LocalInnerClass(); localInner.display(); // 输出:Local inner class } public static void main(String[] args) { OuterClass outer = new OuterClass(); outer.createLocalInnerClass(); } }
- 匿名内部类:
public class OuterClass { public void createAnonymousInnerClass() { Runnable runnable = new Runnable() { @Override public void run() { System.out.println("Anonymous inner class"); } }; new Thread(runnable).start(); // 输出:Anonymous inner class } public static void main(String[] args) { OuterClass outer = new OuterClass(); outer.createAnonymousInnerClass(); } }
- 静态内部类:
public class OuterClass { private static int data = https://www.yisu.com/ask/10;"Accessing outer static member: " + data); } } public static void main(String[] args) { OuterClass.StaticInnerClass staticInner = new OuterClass.StaticInnerClass(); staticInner.accessOuterStaticMember(); // 输出:Accessing outer static member: 10 } }
这些示例展示了如何在Java中使用内部类。内部类可以访问外部类的成员,并且可以根据需要创建实例。