java - Interface-Class-Object,Casting,Exception -
java - Interface-Class-Object,Casting,Exception -
i saw code:
interface i{} class implements i{} class b extends a{} class c extends b{} class abc { public static void main(string args[]) { a=new a(); b b=new b(); a=(b)(i)b; //line 1 b=(b)(i)a; //line 2 a=(i)b; //line 3 i=(c)a; //line 4 } }
trying find out
which way have safe casting i.e without compile time or run time error in circumstances casting show compile time error in circumstances casting show run time exceptioncan 1 explain me these 3 concepts?
in java, interface similar class type. in illustration , object of class oftype , oftype i. object of class b oftype b, oftype(subtype) , oftype i. object of class c oftype c, oftype(subtype) b, oftype(subtype) , oftype i. noticed, objects oftypes of 2 types (te 2 types have no link each other i.e. , independently types) , subtypes of respective super classes.
as per leskov's substitution principal, can sunstiture subtype (sub-class) in place of supertype(super-class). illustrate @ code fragment below:
public class inheritancetest {
public interface i{} public class implements i{} public class b extends a{} public class c extends b{} public class d implements i{} public class e{} public void method(){ a=new a(); b b=new b(); c c=new c(); d d=new d(); i=null; i=a;i=b;i=c; a=b; b=c; a=c; a=(a)i;//a=i not work, , 2 different types i=d; a=(a)i;//classcastexception @ runtime, d not e e=new e(); //a=(a)e; - generates compile time error }//method closing
}//class closing
the cast necessary because, per code, all not i.e. have class d implemented unconnected inheritance hierarchy. in general, when have convert between 2 unconnected types, need cast.
note: have edited code include class d note: have edited code include class e
java object interface casting
Comments
Post a Comment