• Post Reply Bookmark Topic Watch Topic
  • New Topic

generics and inheritance  RSS feed

 
John Smithonian
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I am confused.

At https://docs.oracle.com/javase/tutorial/java/generics/inheritance.html, it states that if A <- B, then it doesn't mean that you can subsitute MyClass<B> in place of MyClass<A>. Fair enough, makes sense.

But then at https://docs.oracle.com/javase/tutorial/java/generics/unboundedWildcards.html it says that "You can insert an Object, or any subtype of Object, into a List<Object>". Why? Just because Object <- AnyClass, surely we cannot substitute MyClass<AnyClass> whenever we have MyClass<Object>.

I find the Java tutorial on Generics confusing, I really do, maybe it isn't and it is just me because I am just trying to rush it, but I find it confusing.
 
Henry Wong
author
Sheriff
Posts: 23291
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

The two snippets are talking about two different things.

For example, an Integer IS-A Number, so an Integer can be used in place of a Number. This means that you can add() an Integer instance into a List<Number>.

This is very different than replacing the generic itself. The second statement doesn't say that an List<Integer> and List<Number> are interchangeable. It is merely saying that an Integer can be managed by a List<Number>, as an Integer IS-A Number.

Henry
 
John Smithonian
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh. So if we have A <- B

Are you saying
MyClass<A> a = new MyClass<B>(); // is wrong, as MyClass<B> doesn't extend MyClass<A>

a.methodOfA(A myArg); // myArg can be an object of type B because B extends A
?

Is this correct?

Thanks.
 
Campbell Ritchie
Marshal
Posts: 56220
171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What happened when you tried to compile that code?
 
John Smithonian
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:What happened when you tried to compile that code?


I didn't, there isn't any point in randonly compiling things without understanding the theory, but I found a tutorial that explains it well, so understand it now.

Thanks.
 
Campbell Ritchie
Marshal
Posts: 56220
171
 
Campbell Ritchie
Marshal
Posts: 56220
171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!