Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

casting among objects

 
bairava surya
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

am perfect with casting among primitives and the above throws an error so help me to understand casting among objects?
 
Henry Wong
author
Marshal
Pie
Posts: 22113
88
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A List<rt> and a List<imp> is not interchangeable in either direction. You can't use a List<rt> in the place of a List<imp>. You also can't use a List<imp> in the place of a List<rt>. So, you can't implicitly cast in either direction.

Of course, if you can explicitly cast, but you will be breaking generics if you do.

Henry
 
Campbell Ritchie
Sheriff
Posts: 51419
87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think it is unfortunate that they applied the same word “casting” to primitives and to reference types.

In the case of primitives you can actually change the type of the variable. In the case of reference types you are simply telling the compiler that a variable will be of a particular type. And in this case, for reasons Henry has already told you and which you can read better here (look also for subtypes), the compiler does not believe you. If the compiler doesn't believe you now, it won't believe you any more if you try again. Read the tutorials and decide whether you really need the cast.
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
bairava surya wrote:am perfect with casting among primitives and the above throws an error so help me to understand casting among objects?

First of all, the above code doesn't throw an error, the above code fails to compile due to a compiler error.

It's hard to explain all rules of casting in a single post. It would require several pages in a study guide to do so. It's quite a complicated topic and if you search this forum (and the OCPJP one) you will find plenty of topics discussing doubts about casting.

These threads contain all valuable information (with code snippets to illustrate rules and possible pitfalls):
  • Why will this throw Class Cast Exception?
  • Casting
  • Not sure why my answer on overloading was incorrect
  • Some doubts about casting
  • instanceof operator with an interface versus class


  • Hope it helps!
    Kind regards,
    Roel
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic