aspose file tools*
The moose likes Java in General and the fly likes Casting and Interfaces Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Casting and Interfaces" Watch "Casting and Interfaces" New topic
Author

Casting and Interfaces

Dale DeMott
Ranch Hand

Joined: Nov 02, 2000
Posts: 515
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

By failing to prepare, you are preparing to fail.<br />Benjamin Franklin (1706 - 1790)
Mark Herschberg
Sheriff

Joined: Dec 04, 2000
Posts: 6037
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

Joined: Apr 02, 2001
Posts: 1157
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

Joined: Nov 02, 2000
Posts: 515
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

Joined: Apr 02, 2001
Posts: 1157
Yes, there are!You may refer to Simon and Roberts Java Certification Guide for more information.
-- Sandeep
 
 
subject: Casting and Interfaces