05. Generic Inheritance

Generics inheritance is a teeny bit tricky because it's different from regular object inheritance, but we'll have all that cleared up in no time!

Take a look at this code.

Integer b = new Integer();
Number a = b;

It runs just fine since Integer is a subclass of Number.

Now let's try the same logic using generics.

ArrayList<Integer> intList = new ArrayList<>();
ArrayList<Object> objList = intList;  // Compile time error

When we try to compile this, we get and error.

Test.java:9: error: incompatible types: ArrayList<Integer> cannot be converted to ArrayList<Object>

We would think that this would work, because Integer is a subclass of Object. However, it doesn't work because generics do not work like that.

generic inheritance in java

ArrayList<Integer> is not subtype of ArrayList<Object>, even though Integer is a subclass of Object. If we want to use generics on a more general level, we need to use wildcards, which are denoted by a ? symbol.

This a very important concept! Make sure you understand this before moving on.

Learn Enterprise Java Development for a Bright Career

Effective Java

Learn Enterprise Java Development for a Bright Career Try Java

Are you looking for a deeper understanding of the Java so that you can write code that is clearer, more correct, more robust, and more reusable? Look no further! Effective Java brings together seventy-eight indispensable programmer's rules of thumb: working, best-practice solutions for the programming challenges you encounter every day.

$ Check price
54.9954.99Amazon 4.5 logo(219+ reviews)

More Java resources

Take your Linux skills to the next level!

System Admin Handbook

Take your Linux skills to the next level! Try Linux & UNIX

This book approaches system administration in a practical way and is an invaluable reference for both new administrators and experienced professionals. It details best practices for every facet of system administration, including storage management, network design and administration, email, web hosting, scripting, and much more.

$ Check price
74.9974.99Amazon 4.5 logo(142+ reviews)

More Linux & UNIX resources

Ad