This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

why compiler shows double standard here?  RSS feed

 
s sivaraman
Ranch Hand
Posts: 59
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator






My question:
compiler allows Interface type down casted to one of its subclass type (line 1)
However,not allows to assign interface type to one of its subclass type reference variable(line2)
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
s sivaraman wrote:
My question:
compiler allows Interface type down casted to one of its subclass type (line 1)
However,not allows to assign interface type to one of its subclass type reference variable(line2)


First of all, do you know what is the difference between an implicit and explicit cast?


Anyway, to answer your question, the reason line 2 fails is because an instance of I may not be IS-A A, and hence, can't be cast implicitly. As for line 1, there isn't any implicit casting needed for the assignment -- as it has been cast explicitly.

Henry
 
Roel De Nijs
Sheriff
Posts: 11338
177
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
s sivaraman wrote:compiler allows Interface type down casted to one of its subclass type (line 1)
However,not allows to assign interface type to one of its subclass type reference variable(line2)

In this thread you'll find a bunch of different casts together with (excellent) explanations about a very similar (almost identical) code snippet. So definitely worth reading as it will probably clear all your doubts.

The rules for casting reference variables can be (very) hard and have a few intricacies. These threads contain all valuable information (with code snippets to illustrate rules and possible pitfalls). So be sure to carefully read all these topics:
  • 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


  • (Note: casting and the instanceof operator are closely related, so the rules are exactly the same)

    Hope it helps!
    Kind regards,
    Roel
     
    It is sorta covered in the JavaRanch Style Guide.
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!