Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, how to distinguish classes that implement the same interface?

Say we have the following interface:

interface Addable {
    Addable add (Addable element);
}

Now I want to declare two classes, say MyList and MyArray that implement the above interface. How can I do this, but prevent a MyArray object being added to a MyList and vice versa?

Is there a way to do this without an if statement and instanceof?

like image 368
user1656804 Avatar asked Jan 27 '26 23:01

user1656804


2 Answers

interface Addable<T extends Addable<T>> {
    T add (T element);
}

class MyList  implements Addable<MyList> {
    public MyList add(MyList element) {
        return null;
    }
}

class MyArray   implements Addable<MyArray> {
    public MyArray add(MyArray element) {
        return null;
    }
}
like image 55
Alexei Kaigorodov Avatar answered Jan 30 '26 11:01

Alexei Kaigorodov


How about changing your interface definition to the following:

    interface Addable<T extends Addable.Element> {
        interface Element { }

        Element add(T element); // OR T add(T element);
    }

    class MyList implements Addable<MyList.MyListElement> {

        static class MyListElement implements Addable.Element { }

        @Override
        public Element add(MyListElement element) {
            return null;
        }
    }


    class MyArray implements Addable<MyArray.MyArrayElement> {
        static class MyArrayElement implements Addable.Element { }

        @Override
        public Element add(MyArrayElement element) {
            return null;
        }
    }


    public static void main(String[] arg) {
        MyArray myArray = new MyArray();
        MyArrayElement a = new MyArrayElement();
        myArray.add(a);

        MyList myList = new MyList();
        MyListElement l = new MyListElement();
        myList.add(l);

        //try to add a MyArrayElement to a MyList
        // Error The method add(MyListElement) in the type MyList
        // is not applicable for the arguments (MyArrayElement)
        myList.add(e);

        //try to add a MyListElement to a MyArray
        // Error The method add(MyArrayElement) in the type MyArray
        // is not applicable for the arguments (MyListElement)
        myArray.add(l);
    }

The wikipedia entry quoted below explains why this works:

Generics are a facility of generic programming that was added to the Java programming language in 2004 as part of J2SE 5.0. They allow "a type or method to operate on objects of various types while providing compile-time type safety."1 A common use of this feature is when using a Java Collection that can hold objects of any type, to specify the specific type of object stored in it.

like image 44
munyengm Avatar answered Jan 30 '26 13:01

munyengm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!