I have this interface:
public interface ISectionListItem {
public int getLayoutId();
public void setProps(View view, int position);
}
But i want all the classes who implements this interface be forces to have a static class inside them. I thought of:
public interface ISectionListItem {
public int getLayoutId();
public void setProps(View view, int position);
static class ViewHolder {};
}
But that dosn’t force the classes to “add unimplemented inner classes”. Anyway to accomplish this? Is it even possible?
Thanks 🙂
This is not possible by the nature of interfaces. An interface defines the public behavior of objects; if a class implements an interface, that means that all instances of that class obey the contract defined by the interface. For this reason interfaces can’t contain static members. (There’s an exception to this rule, but at this point you shouldn’t care about that.)
Be careful of your terminology: static member classes are not inner classes. Static member classes are like normal classes, except that they live in a different namespace. Static member classes are not members of the instances of the containing class, just as any static class member is not part of the “instance template”. An inner class is by definition not static.
So, why can’t we declare a genuine (i.e. non-static) inner class in an interface? That’s because in an interface you can only define the behavior of objects, not how they are composed. The whole point (and beauty) of interfaces is that they separate the behavior (“what does it do”) from the implementation (“how is it done”). For that reason you can’t declare inner classes in an interface, just as you can’t declare fields in an interface.
I don’t know what you’re trying to do, but you might want to try the following. Let’s call your original interface
MyInterface.SomeTypeSomeTypepublic SomeType getInnerClassInstance()(a terrible method name) inMyInterfaceNote that
MyInterfaceinstances aren’t forced to actually return an instance of an inner class as a result ofgetInnerClassInstance(). This is a nice thing, because you’re not bound to a specific implementation.