• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Frits Walraven
Bartenders:
  • Carey Brown
  • salvin francis
  • Claude Moore

Java Generics, Inheritance, and Subtypes.  RSS feed

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
According to Oracle's official Document: https://docs.oracle.com/javase/tutorial/java/generics/inheritance.html

the below code should work as I am passing Object in the case of the generic class since the  generic class IS A Object. But I get a compile time error when invoking the method test.




Could someone explain me why I am getting an error?
 
Marshal
Posts: 64172
215
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, it works the other way round. A Number IS‑AN Object, but it is often the case that An Object ISN'T‑A Number. When you declare a Foo<Number>, and initialise in correctly as you did, the compiler takes that as meaning that all its arguments will be type Number. If you try to add an Object, that Object ISN'T‑A Number, so the compiler goes into strict mode, as you told it to, and rejects that Object. You may only pass anything to a parametrised object if the compiler is sure you are passing something of the correct type.

And welcome to the Ranch
 
Does this tiny ad smell okay to you?
Create Edit Print & Convert PDF Using Free API with Java
https://coderanch.com/wiki/703735/Create-Convert-PDF-Free-Spire
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!