• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Reason for java.lang.ClasscastException

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi
I was try the following code. It compiled file but while running this code I am getting java.lang.ClasscastException. I don't know as why I received this Exception.
Class Superclass
{
int i = 5;
public Superclass()
{
System.out.println("I am in Super Class");
}
public void Method()
{
System.out.println("I am in Method of Super Class");
}
}

class Subclass extends Superclass
{
int i = 10;
public Subclass()
{
System.out.println("I am in Subclass");
}
public void Method()
{
System.out.println("I am in Method of Subclass");
}
}

public class HierarchyInitialization
{
public static void main (String args[])
{
Subclass sb = (Subclass) new Superclass();
sb.Method();
System.out.println("I have completed");
}
}
Can anyone give me the reason, Please.
Krishnan.
 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Let see if I can explain this. A superclass can be assigned to any of its subclasses, and this will compile and run.
ie. SuperClass b = new SubClass();
Because this is possible, it makes sense to have a method to assigned that superclass back to another subclass variable, to go the other way around. Thats what the casting is for.
ie. SubClass a = (SubClass)b;
BUT it is important to note that the object reference 'a' can point to SubClass objects. It can't point to SuperClass objects. Thats what you are doing.
The casting tills Java, hey I know what I am doing, this type conversion is ok. BUT it is still checked at run time. At runtime java says, WAIT you can't assign a subclass reference to a superClass object. This cast is wrong! Error, or more particularly ClassCastError!
What would work is
SuperClass A = new SubClass();
SubClass B = (SubClass)A;
because A points to a subclass object.

hope that helps!
 
Put the moon back where you found it! We need it for tides and poetry and stuff. Like this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic