• Post Reply Bookmark Topic Watch Topic
  • New Topic

Inheritance  RSS feed

 
Ali Sadiq
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

Would someone kindly look at the code below and explain why a class cast exception is thrown at runtime. Thank you!!

class SuperTest {
}

class SubTest extends SuperTest {
}

public class Inheritance {
public static void main(String[] args) {
SubTest subRef = (SubTest) new SuperTest();
// THE ABOVE LINE CAUSES A ClassCastException AT RUNTIME
}
}
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



The question that we should be asking you is... why do you think that it should *not* throw a class cast exception ?

Henry
 
Aum Tao
Ranch Hand
Posts: 210
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From JavaDoc
Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance

Can you apply the IS-A test here? Is SuperTest an instance of SubTest?

Details here:
http://java.sun.com/javase/6/docs/api/java/lang/ClassCastException.html
 
Ali Sadiq
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the info. I guess i need to do more reading on "casting". btw, i changed my screen name.
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One thing you learn is that class-casting is hazardous, risking Exceptions. Another thing you learn is that class-casting is totally different from casting primitives.
 
Aum Tao
Ranch Hand
Posts: 210
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Campbell Ritchie:
One thing you learn is that class-casting is hazardous, risking Exceptions. Another thing you learn is that class-casting is totally different from casting primitives.


This is why, I think, it is a good reason to use the instanceof keyword before casting.
 
yashpal waghmare
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have just changed the names of the class, but structure is same.

here InheritenceS is base class and SubTest is derieved class ,so in Inheritance class you were doing down casting which is not possible so, i have changed one line in Inheritance class, i.e. i have used Up casting now its working fine.
And bug less code is here.


class InheritenceS {
}

class SubTest extends InheritenceS {
}

public class Inheritance {

public static void main(String[] args) {


InheritenceS subRef = (InheritenceS) new SubTest();//yashpal changed this line

// THE ABOVE LINE CAUSES A ClassCastException AT RUNTIME
}
}
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!