• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Downcasting....

 
RajKrishnan Raju
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 637
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).

 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic