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
An interface can't be instantiated directly. Its members are implemented by any class or struct that implements the interface. A class or struct can implement multiple interfaces. A class can inherit a base class and also implement one or more interfaces.
Yes an interface can be implemented by multiple classes.
A class implements an interface if it declares the interface in its implements clause, and provides method bodies for all of the interface's methods. So one way to define an abstract data type in Java is as an interface, with its implementation as a class implementing that interface.
Note: A class can extend a class and can implement any number of interfaces simultaneously.
Yes - you need generics:
interface I <T extends I<T>> {
void add(T foo);
}
To define a class to use it, code it like this:
class C implements I<C> {
@Override
public void add(C foo) {
//
}
}
Note that there is no way to prevent the implementer from coding this (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 coder of class C
knew of the existence of class D
and chose to use it, which is unlikely if they are focused on coding class C
.
Even given this caveat, if I was setting this exam question, I would expect the above to be the answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With