aspose file tools*
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
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: 24187
    
  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]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Downcasting....