Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the use of writing a class inside an interface

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?

like image 222
Anil Kumar C Avatar asked May 11 '12 14:05

Anil Kumar C


People also ask

What is the use of class inside interface?

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.

What is the purpose of writing an interface before implementing a class?

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.

What is the purpose of writing a class in Java?

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.


1 Answers

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).

like image 171
Tomasz Nurkiewicz Avatar answered Oct 20 '22 04:10

Tomasz Nurkiewicz