This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Downcasting.... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Downcasting...." Watch "Downcasting...." New topic
Author

Downcasting....

RajKrishnan Raju
Greenhorn

Joined: May 22, 2005
Posts: 4
Hi,
Iam getting a run time error in this program...Is there any problem in my code???is this not the way of downcasting???


class A
{
public void print()
{
System.out.println("A");
}
}
class B extends A
{
public void print()
{
System.out.println("B");
}
}
public class test
{
public static void main(String s[] )
{

B a = (B) new A();
a.print();
}
}
Stuart Ash
Ranch Hand

Joined: Oct 07, 2005
Posts: 637
Raj,

Please make sure you understand your core object-oriented concepts well. This kind of casting is illegal.

Try Thinking In Java by Bruce Eckel (www.bruceeckel.com).



ASCII silly question, Get a silly ANSI.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Casting a reference type never changes an object in any way. If it's an "A", you can't cast it to a "B". You can cast a "B" to an "A" because a B-is-a-kind-of-A: that's what "extends" means.

I'm moving this to Java in General (Beginner).


[Jess in Action][AskingGoodQuestions]
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Downcasting....
 
Similar Threads
instanceOf Doubt??
Interfaces
Polymorphism and casting
accessability of outerclass members in inner class !!!
Iam Getting runtime Error...(What is Down Casting)