如何实例化这个匿名内部类

package com.lzw;

public class AnonymityInnerClass {
}
class OuterClass4{

public OutInterface doit(final String s){
    return new OutInterface(){
        private int i=0;
        public int getValue(){
            System.out.println(s);
            return i;
            
        }
        public void f(){
            System.out.println("f()");
        }
    };
}

}
interface OutInterface { // 定义一个接口
}

  1. 以上代码直接调用方法会导致找不到方法,因为父类没有子类(匿名内部类)方法,所以无法直接声明式调用
  2. 以下代码使用反射形式进行方法调用
    ```java

import java.lang.reflect.Method;
public class AnonymityInnerClass {
}
class OuterClass4 {
/**
* 测试调用内部类方法
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
OutInterface doit = new OuterClass4().doit("123123");
// 反射获取getValue方法
Method getValueMethod = doit.getClass().getMethod("getValue");
// 执行getValue具体方法
getValueMethod.invoke(doit);
// 反射获取f方法
Method fMethod = doit.getClass().getMethod("f");
// 执行f具体方法
fMethod.invoke(doit);
}

public OutInterface doit(final String s) {
    return new OutInterface() {
        private int i = 0;
        public int getValue() {
            System.out.println(s);
            return i;
        }
        public void f() {
            System.out.println("f()");
        }
    };
}

}
interface OutInterface {
}
```

因为匿名内部类必须是抽象类的子类或者接口的实现类,所以其可以按照下面的步骤实现:

1.编写类,继承这个父类或实现这个接口
2.重写父类或父接口的方法
3.创建这个子类或实现类的对象

new 父类(【实参列表】){
    重写方法...
}
//或者
new 父接口(){
    重写方法...
}

匿名内部类是一种特色的局部内部类,只不过没有名称而已。

使用说明
匿名内部类为局部内部类,所以,局部内部类的所有限制都对其有效

内部类使用外部类

内部类使用成员外部类的资源时,直接访问就可以

外部类使用内部类

局部内部类只能在当前局部(方法)使用,其他地方无法使用,使用的时候通过实例化对象的形式方法。

其他类使用内部类方法

访问不到