I found the following example in one of the java forum.
interface employee{
class Role{
public String rollname;
public int roleId;
public Object person;
}
Role getRole();
// other methods
}
I have executed the above code snippet and it is compiling successfully. Which means we can have a class inside an interface.
My question is what is the use of having such classes? Is it any design pattern?
Java For Testers Yes, you can define a class inside an interface. In general, if the methods of the interface use this class and if we are not using it anywhere else we will declare a class within an interface.
Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler.
A class provides a blueprint for objects of the type of the class. Use the new operator to instantiate (create) the object, followed by a call to the class constructor, which initializes the object's fields.
This code snippet kind of answers your question already. The class Role
is used by the employee
interface in getRole()
method. The designer of the interface decided that this class is so tightly coupled with the interface that it is worth to define it inside that interface to emphasize how important that class is for the interface.
Also it provides semantic namespace for the class: employee.Role
. However I see this kind of construct for the first time while static classes defined inside other classes are quite common (for the same purposes as above).
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