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 .
Nesting classes in interfaces. Despite its strangeness, being able to nest a class inside an interface can be useful, especially when there is a tight relationship between the enclosing interface and the enclosed class. Capturing this relationship improves the source code's readability.
An interface, i.e., declared within another interface or class, is known as a nested interface. The nested interfaces are used to group related interfaces so that they can be easy to maintain. The nested interface must be referred to by the outer interface or class. It can't be accessed directly.
Java inner class or nested class is a class that is declared inside the class or interface. We use inner classes to logically group classes and interfaces in one place to be more readable and maintainable. Additionally, it can access all the members of the outer class, including private data members and methods.
A class is defined inside an interface to bind the interface to a TYPE. In the above interface you are binding the Role type strongly to the employee interface(employee. Role). One more reason is to have modifiable data within an interface(As you may know all fields in an interface are implicitly final).
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With