Q1. Can I have an interface inside a class in java?
Q2. Can I have an class inside an interface?
If yes, then in which situations should such classes/interfaces used.
Q1. Can I have an interface inside a class in java?
Q2. Can I have an class inside an interface?
If yes, then in which situations should such classes/interfaces used.
Q1. Yes Q2. Yes.
Inside your class you may need multiple implementations of an interface, which is only relevant to this particular class. In that case make it an inner interface, rather than a public / package-private one
In your interface you can define some data holder classes that are to be used by implementations and clients.
One example of the latter:
I have faced providing common complex operations for all classes implementing an interface, that use obviously the operations of the interface.
Until Java 8 is not out...
See http://datumedge.blogspot.hu/2012/06/java-8-lambdas.html (Default Methods)
A workaround for this is:
Then you can easily call common functionality (after importing I.U)
May further refined, with some more typical coding:
calling then
A further spicy tricks
The reason for this is to put the operations into a single module instead of having utilities modules hanging around, allowing extendable the worst, duplicated implementation.