File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

runtime exception

 
samdeep aarzoo
Ranch Hand
Posts: 160
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

class A
{
}
class B extends A
{

public static void main(String args[])

{
A s = new A();
B p = (B) s ;
}
}

compiles fine but why runtime exception
please help
 
Kedar Dravid
Ranch Hand
Posts: 333
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You get an exception, because a reference of subclass cannot possibly refer to a supercalss object at runtime.
 
Shaila Vijaya Raja
Greenhorn
Posts: 23
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From your question it's clear that B is the subclass of A

so that

B Bref = new B();
A Aref = Bref;

is possible.

But as we know

A Aref = new A();
B Bref = Aref; This is not possible which leads to a compile time error.

Actually a superclass object cannot be referred by a subclass reference, eventhough you cast it will compilebut leads a runtime error .

Hope you understand..

With Regards
Shaila Vijaya Raja
 
Srinivasa Raghavan
Ranch Hand
Posts: 1228
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To make the concept easy think about this.

java.lang.String extends Object.

So we can say all String's are Object , but all Object's may not be a String.
[ July 16, 2005: Message edited by: Srinivasa Raghavan ]
 
samdeep aarzoo
Ranch Hand
Posts: 160
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thats cool Srinivasa Raghavan
 
Ramakrishna Nalla
Ranch Hand
Posts: 61
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Trying to assign a superclass reference variable to subclass reference variable (child=parent)...is said to be downcasting...and it is possible at run time...



And you have to rememmber :
downcasting an superclass reference variable to an subclass reference
variable is possible only... if the super class variable actually refers to an instance of subclass or an subclass of the subclass....down the hierarchy...

Hope U clear now..

Cheers...
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic