File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes runtime exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "runtime exception " Watch "runtime exception " New topic

runtime exception

samdeep aarzoo
Ranch Hand

Joined: Jun 09, 2005
Posts: 160

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

Joined: May 28, 2004
Posts: 333
You get an exception, because a reference of subclass cannot possibly refer to a supercalss object at runtime.
Shaila Vijaya Raja

Joined: Apr 09, 2005
Posts: 23
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

With Regards,<br />Shaila Vijaya Raja<br /> <br />SCJP1.4
Srinivasa Raghavan
Ranch Hand

Joined: Sep 28, 2004
Posts: 1228
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 ]

Thanks & regards, Srini
MCP, SCJP-1.4, NCFM (Financial Markets), Oracle 9i - SQL ( 1Z0-007 ), ITIL Certified
samdeep aarzoo
Ranch Hand

Joined: Jun 09, 2005
Posts: 160
thats cool Srinivasa Raghavan
Ramakrishna Nalla
Ranch Hand

Joined: Apr 21, 2005
Posts: 61
Trying to assign a superclass reference variable to subclass reference variable (child=parent) 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..

I agree. Here's the link:
subject: runtime exception
It's not a secret anymore!