This week's book giveaway is in the General Computing forum. We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line! See this thread for details.
Hi All, I have one query regarding innterface cast.This is from one of the mocks. Suppose we have 2 classes defined as follows: class base extends object implements Runnable class derived extends base implements Observer Given 2 variables created as follows: base abase = new base(); derived ader=new derived(); which of the following java statements will compile and execute without error.choose all which apply. A.Runnable rn=ader; B.Runnable rn2=(Runnable)abase; C.Observer ob=abase; D.Observer ob2=(Observer)abase; Answers given was a and b. But I didn't understood the interface cast.Could any of you please explain me how it is? Thanks and Regards Priya
Hi Krishna, I think I can explain this (someone correct me if I get it wrong). a. will work as derived class implements Runnable thru it's super class base b. will work as 'abase' class 'base' implements Runnable c. will not work as 'abase' class 'base' does not implement Observer d. will not work for same reason as 'c'; the cast might work at compile time but error will occur at runtime. Basic rule is that you can assign 'up' the inheritance chain ie from derived to base but not vice versa. Hope that helps. ------------------ Jane
Hi, base abase = new base(); derived ader=new derived();
First of all there is no need for casting in
(B) Runnable rn2=(Runnable)abase; //OK
both Runnable rn2=(Runnable)abase; & Runnable rn2 = base; are same
The program will compile and run without any problem even if you give as below
Runnable rn2 = base;
" class Base extends Object implements Runnable"
The above code implies that base is sub class and Object & Runnable are Super. Hence the followings are true
Runnable rn2 = abase; //For Upward no casting is needed Object o = abase; // do
(A) Runnable rn=ader; //OK
The super classes of Derived class are Base, Observer, Runnable (Due to Base)
(C) Observer ob=abase; // NOT OK no relation beteween // Base & Observer
(D) Observer ob2=(Observer)abase; // NOT OK as above // here because of (Observer) casting , the // code compiles happily. But during run time //ClassCastException will be thrown, since during // runtime only object type is checked
Solaiappan
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.