Mar*_* A. 4 java interface local-class
Java 允许我定义本地抽象类,就像在这个例子中一样:
public class Foo {
    public void foo() {
        abstract class Bar {          // Bar is a local class in foo() ...
            abstract void bar();
        }
        new Bar() {                   // ... and can be anonymously instantiated
            void bar() {
                System.out.println("Bar!");
            }
        }.bar();
    }
}
Run Code Online (Sandbox Code Playgroud)
出于某种原因,当我尝试定义“本地接口”而不是本地类时,如下所示:
public class Foo {
    public void foo() {
        interface Bar {           // Bar was supposed to be a local interface...
            void bar();
        }
        new Bar() {               // ... to be anonymously instantiated
            void bar() {
                System.out.println("Bar!");
            }
        }.bar();
    }
}
Run Code Online (Sandbox Code Playgroud)
Java 抱怨“成员接口 Bar 只能在顶级类或接口中定义”。是否有一个原因?还是我错过了我犯的错误?
Java 语言规范并没有告诉您为什么按照原来的方式设计它,但它确实描述了什么是允许的,什么是不允许的。
甲方法体具有以下形式
MethodBody:
    Block 
    ;
Run Code Online (Sandbox Code Playgroud)
Block:
    { BlockStatementsopt }
BlockStatements:
    BlockStatement
    BlockStatements BlockStatement
BlockStatement:
    LocalVariableDeclarationStatement
    ClassDeclaration
    Statement
Run Code Online (Sandbox Code Playgroud)
所以类声明是允许的,但接口不是。
我们可以争辩说,从调用者的角度来看,拥有本地接口并不是很有用。它没有任何用途。接口旨在描述行为,但由于接口是本地的,没有调用者可以使用它。您也可以在类中定义和实现行为。
|   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           1431 次  |  
        
|   最近记录:  |