匿名类扩展

Rol*_*all 1 java anonymous class

声明匿名类时,如下所示:

请注意,ResourceBundle.Control是一个具体的类.

这里取出的片段.

private static void test(Locale locale) {
    ResourceBundle rb = ResourceBundle.getBundle("ResourceBundle", locale,
         new ResourceBundle.Control() {
         @Override
         public List<Locale> getCandidateLocales(String baseName, Locale locale) {
             if (baseName == null)
             throw new NullPointerException();
             if (locale.equals(new Locale("it", "IT"))) {
             return Arrays.asList(
                 locale,
                 Locale.ITALY,
                 Locale.CHINESE ,
                 Locale.ROOT);
             } else if (locale.equals(Locale.GERMANY)) {
             return Arrays.asList(
                 locale.GERMANY,
                 // no Locale.CHINESE here
                 Locale.ROOT);
             }
             return super.getCandidateLocales(baseName, locale);
         }
         });
Run Code Online (Sandbox Code Playgroud)

我基本上看到extends在声明匿名类时它没有使用的关键字.这是理所当然的吗?如果是这样,何时适合extends在匿名类中使用?

提前致谢.

das*_*ght 8

什么时候适合extends在匿名类中使用?

决不.关键字extends适用于命名类,除了扩展类之外,它还可以实现接口.相反,匿名类可以实现接口或扩展类,但不能同时扩展.这就是为什么语法根本没有关键字 - 只需在new表达式后面加上大括号,并为基类或接口的方法提供实现.