问题
The java compiler allows me write a Class definition inside an Interface . Are there any specific uses of this ?
interface ClassInterface {
void returnSomething();
int x = 10;
class SomeClass {
private int y;
private void classDoingSomething() {
}
}
}
Please explain .
回答1:
You would use it to tightly bind a certain type to an interface. Read This page for further information and an example of defining a class inside an interface.
回答2:
The uses are the same that a class nested in another class: it allows scoping the class to the interface. You could imagine something like this:
public interface Switch {
public enum Status {
ON, OFF;
}
void doSwitch();
Status getStatus();
}
It avoids defining a top-level class named SwitchStatus
(because Status
could be a too generic name).
来源:https://stackoverflow.com/questions/9098235/nested-class-inside-an-interface