wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Object Casting Q Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Object Casting Q" Watch "Object Casting Q" New topic
Author

Object Casting Q

Matt DeLacey
Ranch Hand

Joined: Oct 12, 2000
Posts: 318
class T implements Runnable
{
public void run()
{}
}
public class B extends T
{
public static void main(String args[])
{
T t = new T();
B b = new B();
Runnable r = b;
t = (T)r; // Why is the cast needed here?
}
}
Without the cast...it blows up at compilation...WITH the cast it's fine. Can somebody explain in detail why?
Matt
Matt DeLacey
Ranch Hand

Joined: Oct 12, 2000
Posts: 318
Actually I am having a great deal of trouble understanding the rules for Object conversion and casting. I'm looking in RHE (and CERTAINLY no disrepect to those guys out there---they have been a godsend), but I simply cannot understand this concept based on what I'mreading in this text. Is there a good tutorial out there on this. I've been writing code, as you can see above, but I'm REALLY struggling to come to grips with this. I feel like this is my last significant weakness in terms of going for my certification.
Any help would be greatly appreciated.

Matt
Rajiv Ranjan
Ranch Hand

Joined: Sep 28, 2000
Posts: 61
Hey Matt,
Look at the first line of your code
"class T implements Runnable"
This means T is subclass of Runnable.
Now further down in the code you say
T t = new T();
B b = new B();
Runnable r = b;
t = (T)r; // Why is the cast needed here?
Here r has a reference to Superclass whereas t has a reference to sublass and hence this is converting "DOWN" the hierarchy tree which is not desirable.
You can reffer RHE pg. no 117 which has a wonderful explantion on Object reference conversion.
Matt DeLacey
Ranch Hand

Joined: Oct 12, 2000
Posts: 318
Thank you for your reply. I see what you are saying, but the interesting thing is that not only does the code compile with the cast, but IT RUNS ALSO. I was under the impression (and I have seen it happen) where under similar circumstances it blows up at runtime with a classcastexception or something like that. It does not occur here. The other thing is that I have looked at p.117 and find it somewhat confusing. I'm looking for resources OTHER than RHE. I'm sure it is wonderful for most people, but it is not doing the trick (in this one subject) for me. Thanks again for your response.
Matt
Edy
Greenhorn

Joined: Nov 16, 2000
Posts: 4
Let me answer in my own non-technical words.
First, we have to make sure which one is "bigger", t or r?
It's r because t implements r.
Ok, look at the assignment "t = r";
You were trying to put a "bigger" thing "r" into a smaller thing"t", that's why you have to do the explict casting to tell the complier you are willing to lose some parts of bigger "r". And I think that's the basic idea beneath the object casting.
Sorry for my non-tech words.
Rajiv Ranjan
Ranch Hand

Joined: Sep 28, 2000
Posts: 61
Ok Matt , here a small program for you.Hope this will help you as to when it gives classcastexception in runtime.
public class Human
{
public static void main(String args[])
{
System.out.println("I am human");
}
}
public class Man extends Human
{
public static void main(String args[])
{
System.out.println("I am a man");
}
}

Look at this class carefully.

1. public class Woman extends Human
2.{
3. public static void main(String args[])
4. {
5. System.out.println(" I am a woman");
6. Human human = new Man();

7. Woman woman = new Woman();
8. //woman = human; (if you uncomment this line compiler complains)

9. woman =(Woman) human; //(Do this ,it compile but throw an exception during runtime)
10. System.out.println("This test Failed");


}
}
Here I am created a class Woman which extends Human.
Look at line 6 , its perfectly legal as Man in subclass of Human no casting required.
If you uncomment line 8(and comment line 9) compiler complains
as " Explicit cast needed to convert Human to Woman".
So on line 9 we do a explicit casting and it compiled fine.But at runtime the compiler sees that actually human is reference to a Man ,that is, we have tried to equate a man to a woman which upsets compiler and hence a "classcastexception " is thrown at runtime.
Hope this helps........
Paul Anilprem
Enthuware Software Support
Ranch Hand

Joined: Sep 23, 2000
Posts: 3286
    
    7
Matt, IMHO you need "Thinking in Java". Get it for free from www.eckelobjects.com
It is a great book and will clear your OO concepts w.r.t. Java.
-Paul.
------------------
Get Certified, Guaranteed!
(Now Revised for the new Pattern)
www.enthuware.com/jqplus


Enthuware - Best Mock Exams and Questions for Oracle/Sun Java Certifications
Quality Guaranteed - Pass or Full Refund!
lakshmi nair
Ranch Hand

Joined: Oct 11, 2000
Posts: 63
Matt,
Let me put forward some rules which your code follows...
Runnable r = b;
Is ok because b implements Runnable interface through T.
Whenever we convert a class to an interface WITHOUT casting the class must implement that inteface (or its superclasses).
t = (T)r; // Why is the cast needed here?
Now here r is a Interface and t a class. For this to work without a cast, t MUST BE of type Object.All others need a cast.
After the cast, during runtime, since r
contains a reference to b of type B which is a subclass of T, it will work.
Matt DeLacey
Ranch Hand

Joined: Oct 12, 2000
Posts: 318
Thanks to all for their responses. To Rajiv...I understand very well the scenarios you present...thank you very much. It's when you throw interfaces and Objects and arrays into the picture that I am not so clear on. I will get the book you recommend, Paul, thanks for the recommendation.
With Respect,
Matt
Jane Griscti
Ranch Hand

Joined: Aug 30, 2000
Posts: 3141
Hi Matt,
When trying to understand casts I've found you need to think about what the compiler actually knows at compile time.
In your example,

We know 'r' contains a reference to a legal type 'T' based on the instance creation 'b = new B()' and the fact that B extends T BUT the compiler is not quite that smart.
It knows 'r' is delcared Runnable but it's not sure that the object pointed to by 'r' will ALWAYS be assignable to a type 'T'. It therefore requires the cast, giving the programmer the benefit of the doubt ie assumes you will ONLY cast an object that can legally be assigned to type 'T'.
If it turns out, at runtime, that 'b' was not of a type that could be legally assigned to type 'T'; a runtime error will be thrown.
Regardless of the type, wether a class, interface, or array if you can work through what the compiler is sure of at compile time you can usually determine when and why you need a cast.
Hope that helps.

------------------
Jane
The cure for boredom is curiosity.
There is no cure for curiosity.
-- Dorothy Parker
[This message has been edited by Jane Griscti (edited November 17, 2000).]


Jane Griscti
SCJP, Co-author Mike Meyers' Java 2 Certification Passport
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Object Casting Q