| Author |
Casting and Interfaces
|
Dale DeMott
Ranch Hand
Joined: Nov 02, 2000
Posts: 514
|
|
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
|
<b>Sandeep</b> <br /> <br /><b>Sun Certified Programmer for Java 2 Platform</b><br /> <br /><b>Oracle Certified Solution Developer - JDeveloper</b><br /><b>-- Oracle JDeveloper Rel. 3.0 - Develop Database Applications with Java </b><br /><b>-- Object-Oriented Analysis and Design with UML</b><br /> <br /><b>Oracle Certified Enterprise Developer - Oracle Internet Platform</b><br /><b>-- Enterprise Connectivity with J2EE </b><br /><b>-- Enterprise Development on the Oracle Internet Platform </b>
|
 |
Dale DeMott
Ranch Hand
Joined: Nov 02, 2000
Posts: 514
|
|
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
|
|
|