Win a copy of Succeeding with AI 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
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
  • Junilu Lacar
Sheriffs:
  • Tim Cooke
  • Jeanne Boyarsky
  • Knute Snortum
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:
  • salvin francis
  • fred rosenberger
  • Frits Walraven

coverting sub class object to super class object

 
Ranch Hand
Posts: 502
jQuery Spring Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Y is a subclass of class X. will this compile?

Class X objX = new Class X();
Class Y y= (Class Y) objX;

Ans: YES.

can anybody explain me why?

thanks!
Prabhu
 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
please read about casting
what you are doing is down casting
the class x object to class y
 
tim bond
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Y is a subclass of class X. will this compile?

Class X objX = new Class X();
Class Y y= (Class Y) objX;

Ans: YES.

can anybody explain me why?


Class X objX = new Class X();
objx is an object of class x



class x is the superclass of class y



Class Y y= (Class Y) objX;

here you are creating a reference y (not an object)
and objx is being assigned to this reference y.
and the objx is being downcasted using (Class y).

thats why it is getting compiled.
 
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This will not give any compile time error as you are explicitly type casting it.
So, the compiler will assume that whatever you are doing in explicit type casting is know to & you are responsible for that.so it will over look the error. But in run time it will give error.
 
Just the other day, I was thinking ... about this tiny 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