• 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 ...
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Paul Clapham
  • Jeanne Boyarsky
  • Devaka Cooray
  • Junilu Lacar
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Tim Holloway
  • Claude Moore
  • Stephan van Hulst
  • Winston Gutkowski
  • Carey Brown
  • Frits Walraven

Java Generics, Inheritance, and Subtypes.  RSS feed

Posts: 3
  • 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?
Posts: 63454
  • 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
"I know this defies the law of gravity... but I never studied law." -B. Bunny Defiant tiny ad:
Become a Java guru with IntelliJ IDEA
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!