aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Need Help Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Need Help" Watch "Need Help" New topic
Author

Need Help

Vivek Shrivastava
Ranch Hand

Joined: Jun 03, 2000
Posts: 277


HI,
I need comments from java expert for following two problems.(I understand the rule of one thread one question but both of my questions are related to a one topic so please don't mind)
1. An interface can never be implicitly converted to any refrence type other than Object.
2. An array may be converted to the class Object,to the interface Cloneable or Serializable or to an array.
I really don't understand the concept 100%. so please explain it to me.
regards
vivek
Paul Smiley
Ranch Hand

Joined: Jun 02, 2000
Posts: 244
Not positive about this, but since an interface can extend other interfaces, it would appear that you can do a widening cast between the two.
Vivek Shrivastava
Ranch Hand

Joined: Jun 03, 2000
Posts: 277
can some one else put some light here. i am really confuse. it would be a great help.
vivek
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18670
Well, statement 1 isn't true:
<code><pre>
interface A {
void methodA();
}

interface B extends A {
void methodB();
}

class Test {
public static void main(String[] s) {
A a = new A() {
void methodA() {}
}
B b = new B() {
void methodA() {}
void methodB() {}
}
a = b; // legal - type B is implicitly converted to A
}
}
</pre></code>
The second is true though:
<code><pre> int[] myArray = {1, 2, 3, 4};
Object obj = myArray;
Cloneable cl = myArray;
Serializable ser = myArray;</pre></code>
All are legal. This also means you can treat myArray as an Object, Cloneable, or Serializable even without declaring the class:
<code><pre> myArray.toString(); // uses toString() defined in Object
myArray.toString(); // won't throw CloneNotSupportedException
someObjectOutputStream.writeObject(myArray); // won't throw NotSerializableException
</pre></code>

"I'm not back." - Bill Harding, Twister
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
hi,
I quote from jls 5.4.1 for widening reference conversions
in case of interfaces
From any interface type J to any interface type K, provided that J is a subinterface of K.
From any interface type to type Object

in case of arrays.
From any array type to type Object.
From any array type to type Cloneable.
From any array type SC[] to any array type TC[], provided that SC and TC are reference types and there is a widening conversion from SC to TC.
in case of arrays one can convert to Cloneable and Serializable as every array implement these interfaces.
regds.
Rahul
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Need Help
 
Similar Threads
Object Conversion Rules!Pls help me!
instanceof
Conversion of Objects
What it means
Object reference conversion