hi this following code is showing some runtime error as "Exception in thread "main" java.lang.ClassCastException: A at Cast.main(Cast.java:24)" in the following code
hi so that means i can never do a upcast in case of derived data types. means i can never refer to a super class object by a sub class reference. if it is like that than what is the use of type cast in case of these derived data types. please explain me this cating concept that which ever things i can cast and what are the things i cannot cast.
Originally posted by PUNEET MITTAL: hi so that means i can never do a upcast in case of derived data types. means i can never refer to a super class object by a sub class reference.
Incorrect on two counts. First, what you're talking--casting from a superclass to a subclass--is called a downcast, not an upcast. Second, if the object really is an instance of the subclass, downcasting works just fine. In your own example, a2 is really a B, so this will work:
i want to say that in this following code, if i want it to run properly without any errors than what will be the procedure, means if i want an object of class A to be referred by object of class B, so can i do this or not. And if i cannot do this than why do we really need an upcasting.
error while running at line highlighted: Exception in thread "main" java.lang.ClassCastException: A at Cast.main(Cast.java:24)
Please read the previous replies, which have explained clearly and carefully why that particular cast is impossible. And please don't write things (including the title of the thread) in ALL UPPERCASE.
hi campbell thanks, i got the answer but what exactly i am asking is that, when i cannot cast an object that has a runtime type of superclass to a subclass, then why is this upcasting required. please explain me this upcasting concept, that when can we do upcasting???
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32833
4
posted
0
Upcasting means casting to a more generalised form, or less specialised form. You can upcast String to Object. It does mean, however, that only methods in the superclass you are casting to are accessible.
Alan Moore
Ranch Hand
Joined: May 06, 2004
Posts: 262
posted
0
Originally posted by PUNEET MITTAL: hi campbell thanks, i got the answer but what exactly i am asking is that, when i cannot cast an object that has a runtime type of superclass to a subclass, then why is this upcasting required. please explain me this upcasting concept, that when can we do upcasting???
Ideally, downcasting is something you would never have to do at all, because it undermines the built-in type safety of the language. With the addition of generics in Java 5, downcasting is necessary much less often than it was before, but it's still farily common. We as programmers just have to do everything we can to make sure the object really is an instance of the subclass before we cast it.