I
iamrichardjones
Hi All,
I ahve a question about casting to object and interfaces. Consider the
following code:
---------------------------------------------------------------------------------------------------------------------
package Test
interface RandomInterface{}
class SubClass1 {}
class SubClass2 {}
public class Test {
public static void main(String... args){
SubClass1 subClass1 = new SubClass1();
SubClass2 subClass2 = new SubClass2();
RandomInterface i = (RandomInterface) subClass1; //throws
ClassCastException
SubClass2 newReference = (SubClass2)subClass1; //wont compile
}
}
---------------------------------------------------------------------------------------------------------------------
When I cast subClass1 to RandomInterface I get a ClassCastException at
runtime. However if I try and cast subClass1 to SubClass2 then I get a
compile time error. Does java apply different casting rules to class
and interfaces?
Thanks in advance
Richard
I ahve a question about casting to object and interfaces. Consider the
following code:
---------------------------------------------------------------------------------------------------------------------
package Test
interface RandomInterface{}
class SubClass1 {}
class SubClass2 {}
public class Test {
public static void main(String... args){
SubClass1 subClass1 = new SubClass1();
SubClass2 subClass2 = new SubClass2();
RandomInterface i = (RandomInterface) subClass1; //throws
ClassCastException
SubClass2 newReference = (SubClass2)subClass1; //wont compile
}
}
---------------------------------------------------------------------------------------------------------------------
When I cast subClass1 to RandomInterface I get a ClassCastException at
runtime. However if I try and cast subClass1 to SubClass2 then I get a
compile time error. Does java apply different casting rules to class
and interfaces?
Thanks in advance
Richard