Let’s say I have an interface in Java:
interface I {
void add(I foo);
}
, and also two classes C and D that implement this interface.
Is there any way I can modify the interface such that I could only do:
C c = new C();
c.add(new C());
, but not
c.add(new D());
?
I had this question on an exam, but my only idea was to use the instanceof operator in the definition of the method:
class C implements I {
public void add(I foo) {
if (foo instanceof C) {
System.out.println("instance of C");
} else {
System.out.println("another instance");
}
}
}
However, I don’t know how to modify the interface such that I produce the same effect.
Thanks
Yes – you need generics:
To define a class to use it, code it like this:
Note that there is no way to prevent the implementer from coding this (assuming
Dalso implementsI):However, this would only be a problem if the coder of class
Cknew of the existence of classDand chose to use it, which is unlikely if they are focused on coding classC.Even given this caveat, if I was setting this exam question, I would expect the above to be the answer.