This week's book giveaway is in the Artificial Intelligence and Machine Learning forum.
We're giving away four copies of Transfer Learning for Natural Language Processing (MEAP) and have Paul Azunre on-line!
See this thread for details.
Win a copy of Transfer Learning for Natural Language Processing (MEAP) this week in the Artificial Intelligence and Machine Learning forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Paul Clapham
  • Devaka Cooray
  • Bear Bibeault
Sheriffs:
  • Junilu Lacar
  • Knute Snortum
  • Liutauras Vilda
Saloon Keepers:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Piet Souris
Bartenders:
  • salvin francis
  • Carey Brown
  • Frits Walraven

class/ subclass

 
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I still have some doubts on the question posed by Rajendra Deshpande :
He wrote :
Hi,
Here is a question that appeared in a mock test.
class Y is a subclass of X. Will this compile?
X myX = new X();
Y myY = (Y) myX;
As i am given to understand, a class can be casted(hope i am using right term)to its superclass, but here we have (Y) myX,
where Y is a subclass of X. I think this should not compile.
However the correct answer appears to be is 'will compile' but 'not run'. Can someone shed light on this.

thanks.
-----------------------------------------------------------
My Doubt :
In this case the reference myX is initially initialized to an X object. On the second line we are downcasting it to a Y object which is a subclass of X.
The answer given was that compiler does not know till run time whether myX represents an X object or a Y object So it compiles. But during run time it is detected that the object is actually an X object. So it throws a ClassCastException (am i right here??).
My question is why isn't the compiler able to detect that the reference is pointing to an X object (even though the object is yet to be created) at compile time even though an explicit instantiation is made (x myX=new X()).
SJ
 
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sajan,
Refer to Carl's post in the original thread. Looks like that is the rule of the game.
thanks and regards,
-Rajendra.
 
Evil is afoot. But this tiny ad is just an ad:
Two software engineers solve most of the world's problems in one K&R sized book
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic