• Post Reply Bookmark Topic Watch Topic
  • New Topic

Object reference  RSS feed

 
Rd Dari
Ranch Hand
Posts: 214
Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is a question which I have faced in my recently interview, what correct answer should be of that:

Q: Will it compile?

X myx=new X();
Y myy=(Y) myx;

The option is:

a) Yes
b) No
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In which condition can you cast an object to a different class ?
 
Rd Dari
Ranch Hand
Posts: 214
Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think no... and my answer is NO.
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not asking yes or no. I'm asking in which condition can you cast an object to a different class ?
 
Ralph Cook
Ranch Hand
Posts: 479
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The question is incomplete. You cannot say whether this will compile without knowing the class declarations of X and Y.

If we use String and Integer instead, eclipse (at least) tells me I cannot cast a String to an Integer.

If it were possible that the object referenced were compatible with the type being cast, then I think you could do the cast; it would fail at runtime if the cast could not succeed. But if the compiler can tell there is no way for it to succeed, it tells you when you compile.

So to answer the second poster's question: you can have the compiler handle this when the classes are possibly compatible, and you can have the runtime handle it when the objects' classes are actually compatible.
 
Rd Dari
Ranch Hand
Posts: 214
Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Christophe Verré wrote:I'm not asking yes or no. I'm asking in which condition can you cast an object to a different class ?




Sir I can't explain it, but in fact I want to know of its right answer. The question was as its in the written test paper at the interview time.
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As Ralph explained, you cannot say whether it's yes or no unless you know the relation between X and Y.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!