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.

Take your Linux skills to the next level!

Command Line Kung Fu

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

Command Line Kung Fu is packed with dozens of tips and practical real-world examples. You won't find theoretical examples in this book. The examples demonstrate how to solve actual problems. The tactics are easy to find, too. Each chapter covers a specific topic and groups related tips and examples together.

$ Check price
14.9914.99Amazon 4.5 logo(27+ reviews)

More Linux & UNIX resources

Learn Enterprise Java Development for a Bright Career

Java, A Beginner's Guide

Learn Enterprise Java Development for a Bright Career Try Java

A book that is simple, direct, terse with easy examples. Simple example programs to guide you as you go, with test exercises at the end for you to judge for yourself how well you understand the program. Learn java faster and efficiently with Java: A Beginner's Guide.

$ Check price
4040Amazon 4.5 logo(245+ reviews)

More Java resources

Ad