举一个内部类、局部内部类、静态内部类、匿名内部类的代码例子。
时间: 2023-11-06 16:08:13 浏览: 74
java 内部类 局部内部类 匿名类 实例代码
5星 · 资源好评率100%
内部类、局部内部类、静态内部类、匿名内部类的代码例子如下:
1. 成员内部类的例子:
```
public class OuterClass {
private int x = 10;
public class InnerClass {
public void printX() {
System.out.println("x is " + x);
}
}
}
```
2. 局部内部类的例子:
```
public class OuterClass {
private int x = 10;
public void printX() {
class LocalInnerClass {
public void printOuterX() {
System.out.println("Outer x is " + x);
}
}
LocalInnerClass localInner = new LocalInnerClass();
localInner.printOuterX();
}
}
```
3. 静态内部类的例子:
```
public class OuterClass {
private static int x = 10;
public static class StaticInnerClass {
public void printX() {
System.out.println("x is " + x);
}
}
}
```
4. 匿名内部类的例子:
```
public class OuterClass {
public void printMessage() {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Hello from anonymous inner class!");
}
}).start();
}
}
```
阅读全文