Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Casting and Interfaces

 
Dale DeMott
Ranch Hand
Posts: 515
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So I'm confused about interfaces and casting. I understand object casting and when casting is legal with arrays but how do interfaces fit into all of this?
Anyone an expert out there in casting and converting.. and how interfaces fit into this??
Dale
 
Mark Herschberg
Sheriff
Posts: 6037
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can cast to an interface just as easily as you can cast to a class. Basically, when casting, you say, I want to just look at one aspect of this object, and consider only the methods available from that aspect. Consider:

now if I have a method in some class

when I make the call

I'm implicitly casting mc to the interface Foo. Within doSomething(), I can only access the Foo methods: mth_foo_get(), mth_foo_set().
If I try to call a Bar method within doSomething(), i.e. mth_bar_seek() or mth_bar_put(), I'll get a compiler error. This is because although I happened to pass in a MyClass object, which implements Bar, the method doSomething() doesn't know that. I may call it from another place with an object only implementing the Foo interface.
I can, however, within doSoemthing() have the following code:


Of course, you don't need a method call to do this type of cast. The same holds true even if you did an explicit cast:


--Mark
[This message has been edited by Mark Herschberg (edited July 12, 2001).]
 
Desai Sandeep
Ranch Hand
Posts: 1157
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is exactly how most of the classes are designed.You call it programming to an interface.Instead of calling methods on concrete classes you call methods using the reference of the interface.The advantage you get is that if the interface changes, you would not require to change the implementation.
-- Sandeep
 
Dale DeMott
Ranch Hand
Posts: 515
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are there any general rules for implict and explict casting for interfaces?
------------------
By failing to prepare, you are preparing to fail.
Benjamin Franklin (1706 - 1790)
 
Desai Sandeep
Ranch Hand
Posts: 1157
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, there are!You may refer to Simon and Roberts Java Certification Guide for more information.
-- Sandeep
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic