Search code examples
javaobjectgenericssuperclasssuper

How super keyword work with Object


Am Using super for Runnable interface and define Object type to store there am not get any compile error, but for the below code MyRunnale(i) am using MyObject to store but compiler raise a compile error: Type mismatch
Please explain me why am getting compile error & why it is getting there.

class Test 
{

    public static void main(String[] args) {
        ArrayList<? super Runnable> a1 = new ArrayList<Object>();
        // Here am not getting any CTE but for the below code
        ArrayList<? super MyRunnable> a2 = new ArrayList<MyObject>();
        // compile error: Type mismatch: cannot convert from ArrayList<MyObject> to
        // ArrayList<? super MyRunnable>
    }
}

class MyObject {
}
interface MyRunnable {
}
class MyThread extends MyObject implements MyRunnable {
}

Solution

  • When you use ArrayList<? super Runnable>, it means the ArrayList can refer to a ArryList of Runnable and any super type of Runnable (In this case ArrayList<Runnable>() or ArrayList<Object>()).

    But MyObject is a sub type of Runnable. Hence it doesn't allow you to assign an ArrayList<MyObject>() to it.

    If you want to refer ArrayList<MyObject>(), you should use ArrayList<? extends Runnable>.

    But make sure you satisfy the PECS rule.