Skip to content Skip to sidebar Skip to footer

How To Add A Class Implementing An Interface To An Arraylist

To go around having to implement ALL the methods in an interface, I created an abstract class that implements an interface, then have other classes extend the abstract class and ov

Solution 1:

you need to use wildcard ? extends IMyInterface.

ArrayList<Class<?extends IMyInterface>> classes = new ArrayList<>();

In ArrayList<Class<IMyInterface>> classes , you can only add Class<IMyInterface>.

Solution 2:

Solution 3:

I am able to add this way, hope this is helpful

publicclassMyClassextendsAbstractIMyInterface {
    @OverridepublicvoidonEating() {
        //from interface
    }

    @OverridevoidonRunning() {
        //from abstract
    }

    publicstaticvoidmain(String[] args){

        ArrayList<IMyInterface> iMyInterfaces = newArrayList<>();
        MyClass myClass = newMyClass();
        iMyInterfaces.add(myClass);

    }
}

Post a Comment for "How To Add A Class Implementing An Interface To An Arraylist"