• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Object Casting Q

 
Ranch Hand
Posts: 318
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 318
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 318
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 61
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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........
 
Enthuware Software Support
Posts: 4810
52
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 318
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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).]
 
This looks like a job for .... legal tender! It says so right in this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic