Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

casting with interface

 
Harshana Dias
Ranch Hand
Posts: 333
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey,

Can we cast a interface to an object?

I mean,



But other way works know,


Thank You.
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Would look like this..

 
Harshana Dias
Ranch Hand
Posts: 333
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So it means right hand side be a object that implements the interface right? not just the interface it self
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well the only way is to have a concrete class implementing the interface.

An interface is an abstract contract that the implementing class has to fulfill. How would you want to instantiate the interface itself?

The ONLY case when you could instantiate an interface is using an anonymous class, hence automatically building an implementer.
 
Jarred Olson
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This may help.



Depending on which object is randomly created your output will be either:

A's doStuff() method.
Special A Code.

or:

B's doStuff() method.
Special B Code.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic