The class implementation interface should be able to add only an object of the same class

Say I have an interface in Java:

interface I { void add(I foo); } 

as well as two classes C and D that implement this interface.

Is there any way to change the interface , which I could only do:

 C c = new C(); c.add(new C()); 

but not

 c.add(new D()); 

?

I had this question in the exam, but my only idea was to use the instanceof operator in the method definition:

 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 do not know how to change the interface so that I create the same effect.

thanks

+6
source share
1 answer

Yes - you need generics:

 interface I <T extends I<T>> { void add(T foo); } 

To define a class to use, enter it like this:

 class C implements I<C> { @Override public void add(C foo) { // } } 

Note that there is no way to prevent the coding of this implementer (assuming D also implements I ):

 class C implements I<D> { @Override public void add(D foo) { // } } 

However, this would only be a problem if the class C encoder knew about the existence of class D and decided to use it, which is unlikely if they focus on the C encoding class.

Even with this caution, if I asked this exam question, I would expect this to be the answer.

+7
source

Source: https://habr.com/ru/post/925951/


All Articles