Win a copy of The Business Blockchain this week in the Cloud forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why compiler shows double standard here?

 
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
Marshal
Pie
Posts: 22086
88
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: 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
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
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic