Author | Topic: Object Reference Casting |
Shiva ranch hand |
posted April 08, 2000 09:36 PM
can we cast an interface to a non final class? according to SRH p.117(1,3) Old Type is an interface, new Type is a Non final class it says " Always OK" but when i try to run this it says Incompatible Type am i missing something, Thanks in advance code: ------------------
[This message has been edited by maha anna (edited April 10, 2000).]
|
maha anna bartender |
posted April 10, 2000 11:39 AM
Shiva, Any non-final normal class can be casted and assigned to a ref of an Interface. As long as you put cast it correctly it is Always OK . I think you are thinking about 'conversion'. For conversion, the right hand side (oldtype) MUST implement the interface. You have to know the difference between 'casting' and 'conversion'. When we say Also note that the table in R&H at page 117 is Compile time Rules for Object reference Casting Is this clear to you now Shiva? [This message has been edited by maha anna (edited April 10, 2000).]
|
Shiva ranch hand |
posted April 10, 2000 01:28 PM
Hi Maha, i mixed up the words i should have said "Reference Assignment Conversions" when i hunt for some other references found this, if old type is an interface type, oldRef can be assigned to newRef provided newRef type is Object//** this creates a new querry in my mind if you can assign an interface type to an Object type MyInterface M1; Object obRef = new Object(); obRef = M1;// ok cauz its superclass of all types but if i create class MyClass implements MyInterface{ // } MyClass mcl = new MyClass(); interface so when you upcast its ok and when you downcast need explicit cast(does this rule applies here) i think i need to goback to Thinking in java again" Regards, Shiva ------------------
|
maha anna bartender |
posted April 10, 2000 02:58 PM
Shiva, if old type is an interface type, oldRef can be assigned to newRef provided newRef type is Object - is exactly true. In fact it can be assigned ONLY to an object of type Object. - In java, all ref type (class/interface/array) ALL decend from Object class. - And also there is no hirerarchy idea of if a class implement an interface then , the interface ref can be converted to the class. Actuaally it is the other way around. If a class implemnents an interface then the a reference to an object which is of that particular class type CAN BE CONVERTED to the interface which the class implements. In other words, I stop here itself. Now I leave you to explore Thinking in Java. [This message has been edited by maha anna (edited April 10, 2000).]
|
Shiva ranch hand |
posted April 10, 2000 06:27 PM
Thank you so much Maha anna for your detail information, it cleared my doubts about interface
------------------
|
| | |