This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

runtime exception

 
samdeep aarzoo
Ranch Hand
Posts: 160
  • 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
  • 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
  • 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
  • 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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thats cool Srinivasa Raghavan
 
Ramakrishna Nalla
Ranch Hand
Posts: 61
  • 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...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic