成员内部类与局部内部类,代码举例说明
时间: 2023-05-23 10:02:16 浏览: 92
Java的内部类讲解案例代码(成员内部类、局部内部类、匿名内部类、静态内部类、外部类访问四种内部类、其他类访问四种内部类...)
好的,下面是成员内部类和局部内部类的例子:
成员内部类:
```java
public class OuterClass {
private int x = 10;
class InnerClass {
public int getNum() {
System.out.println("This is the getnum method of the inner class");
return x;
}
}
}
public class Main {
public static void main(String[] args) {
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
System.out.println(inner.getNum()); // 输出 10
}
}
```
局部内部类:
```java
public class OuterClass {
private int x = 10;
void doSomething() {
class InnerClass {
public void print() {
System.out.println("This is the print method of the inner class");
}
}
InnerClass inner = new InnerClass();
inner.print(); // 输出 This is the print method of the inner class
}
}
public class Main {
public static void main(String[] args) {
OuterClass outer = new OuterClass();
outer.doSomething();
}
}
```
希望能帮到你!
阅读全文