This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Interface and Casting

 
Lakshmi Saradha
Ranch Hand
Posts: 170
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I came acroos this questions in Brogden's site.
import java.util.*;
class ApBase extends Object implements Runnable{public void run() {}}
class ApDerived extends ApBase implements Observer {public void update(Observable o,Object arg ) {}}
class A {
public static void main (String args[]) {
ApBase abase = new ApBase();
ApDerived ader = new ApDerived();
}}
The question was 'Which of teh following will compile and execute without error?'
The options given are:
1)Object obj = abase;
Runnable rn = obj;
2) Object obj = abase;
Runnable rn = (Runnable)obj;
3)Object obj = abase;
Observer ob = (Observer)abase;
4)Object obj= ader;
Observer o = obj.
The correct ans is b). I understood that 1) is a wrong option.

Could you help me in finding out why b) is right and why c) and d) are wrong?
Also could any one sugegst a good reading material on this topic?

I am totally lost

 
Ray Stojonic
Ranch Hand
Posts: 326
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Lakshmi,
2 is correct because:
Object obj = abase;
abase is a ApBase reference to an ApBase object, which is extended from Object, this is a widening assignment, no cast required.
Runnable rn = (Runnable)obj;
obj is an Object reference to an ApBase object, which implements Runnable, this is a narrowing assignment, implicit cast required. At compile time it is assumed that the cast will be valid. At runtime, the cast is valid, no error.
3 is wrong because:
Object obj = abase;
This is fine, as above
Observer ob = (Observer)abase;
abase is an ApBase reference to an ApBase object, class ApBase has nothing to do with Observer. Observer is an interface, so it's assumed at compile time that the object referred to by abase will be able to be cast to an Observer object, compiles fine. At runtime this is found to not be the case, ClassCastException occurs.
4 is wrong because:
Object obj= ader;
This is fine, as above, but with ApDerived object
Observer o = obj.
Object to Observer is a narrowing assignment, implicit cast required.

hope that helps
 
Lakshmi Saradha
Ranch Hand
Posts: 170
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Ray.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic