Results 1 to 8 of 8
- 01-28-2010, 08:37 AM #1
Casting a child class into a parent class.
Hi there, new to the forums and plan on staying for a very very long time. :o
My question, as the title states:
-Is it possible to cast an object of a child class into an object of its parent class and if so, how is it coded?
This is what I've been tinkering with thus far..
Example:
ChildClass a = new ChildClass();
ParentClass b = (ChildClass)a;
-UnsubLast edited by Unsub; 01-28-2010 at 08:37 AM. Reason: edit 1: added example
- 01-28-2010, 08:49 AM #2
Senior Member
- Join Date
- Aug 2009
- Posts
- 2,388
- Rep Power
- 6
The ChildClass object is already a ParentClass object so there is no need to cast.
Putting the cast is just redundant.
- 01-28-2010, 08:54 AM #3
Last edited by Unsub; 01-28-2010 at 08:59 AM. Reason: edit: #1:Fixed quote
- 01-28-2010, 09:07 AM #4
Senior Member
- Join Date
- Aug 2009
- Posts
- 2,388
- Rep Power
- 6
You can. The compiler won't complain. You could get a runtime exception though if the object cannot be cast to that type at runtime.
- 01-28-2010, 10:07 AM #5
Member
- Join Date
- Jan 2010
- Posts
- 21
- Rep Power
- 0
Casting related to inheritance
Here by i give the casting procedures and problems,related to inheritance
superclass=subclass (This is valid)
subclass=(subclass)superclass (This is valid at compile time but shows an error in run time-ClassCastException)
subclass=superclass (Shows error in compile time itself)
- 01-28-2010, 11:53 AM #6
Moderator
- Join Date
- Apr 2009
- Posts
- 10,468
- Rep Power
- 16
No it doesn't...see:subclass=(subclass)superclass (This is valid at compile time but shows an error in run time-ClassCastException)
is perfectly valid at runtime.Java Code:Superclass superc = new Subclass(); Subclass subc = (Subclass) superc;
- 01-28-2010, 02:04 PM #7
I think I understand now. Thanks everyone.
- 01-30-2010, 01:39 AM #8
Member
- Join Date
- Nov 2009
- Posts
- 26
- Rep Power
- 0
Similar Threads
-
how to get the child class in inheritance?
By java_fun2007 in forum New To JavaReplies: 7Last Post: 09-29-2010, 09:35 AM -
Child-Class Calling a Method in a Parent-Class
By Blah_ in forum New To JavaReplies: 5Last Post: 09-29-2009, 02:48 AM -
[SOLVED] How to pass information from child class to parent class
By pellebye in forum New To JavaReplies: 7Last Post: 05-06-2009, 12:42 PM -
Parent & Child window issues......
By jithan in forum New To JavaReplies: 2Last Post: 09-20-2008, 09:21 AM -
class casting
By vital parsley in forum New To JavaReplies: 1Last Post: 07-24-2008, 10:03 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks