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.
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
This a very important concept! Make sure you understand this before moving on.
Jump start your Java education with Head First Java! This book provides clean diagram examples, with text that is easy-to-understand in an almost too-casual language. Great for anyone new to Java or programming in general.$ Check price
Linux for Beginners doesn't make any assumptions about your background or knowledge of Linux. You need no prior knowledge to benefit from this book. You will be guided step by step using a logical and systematic approach. As new concepts, commands, or jargon are encountered they are explained in plain language, making it easy for anyone to understand.$ Check price