Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class implementing interface should be able to only add an object of the same class

Tags:

java

generics

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

like image 565
Claudiu Avatar asked Sep 21 '12 19:09

Claudiu


People also ask

Can an interface be implemented by a class?

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.

Does an interface can be implemented by multiple classes?

Yes an interface can be implemented by multiple classes.

When should a class implement an interface?

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.

Can a class implement an interface and extend a class at the same time?

Note: A class can extend a class and can implement any number of interfaces simultaneously.


1 Answers

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.

like image 150
Bohemian Avatar answered Oct 30 '22 03:10

Bohemian