interface with in an abstract class
-
21-12-2019 - |
Question
Is it possible to declare an interface inside an abstract class ?. I tried this and i was successfully able to do it without any compilation error?? In Practical usage is there any significance of this ??
Here is the code that i have wrote.
public abstract class X
{
public interface abc extends I1
{
public void sum(int i,int j);
}
}
public class Impl extends X
{
class InnerImpl implements abc
{
@Override
public int sum(int i, int j)
{
return i+j;
}
}
}
public interface I1
{
}
Solution
You can declare an interface within any class, not just abstract. The interface is implicitly static
, so your enclosing class is just providing a namespace scope and is otherwise unrelated to the interface.
The utility of this definitely exists and I have used it on a number of occasions. Often the interface is coupled to a method of the same class, so clients can pass implementations of that interface to the method.
With Java 8 and functional interface types the proliferation of local interfaces will only increase.
OTHER TIPS
Yes it is possible. As you said - it compiles (and I imagine runs), so it's legal.
In fact it is legal to declare a subinterface in an interface, or an enum (but only public ones, as private ones don't make any sense in an interface, just like private methods).
As for practical uses: You can declare a private inner class in your abstract class and use it in methods of said abstract class (I hope you can think of a usage for that). Or two of those. And if you need a shared contract for both - you can use an interface. Or you would need to return a specific thing that doesn't make sense outside the parent class.
A more down-to-earth example is the interface Map
and it's sub-interface Map.Entry
. Some methods of Map
return and Entry
, yet entry is meaningless without Map
, so is not a standalone interface. If Map
was an abstract class rather than an interface you would have exactly the situation you described.