File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Casting between classes. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Casting between classes." Watch "Casting between classes." New topic
Author

Casting between classes.

Rob Brew
Ranch Hand

Joined: Jun 23, 2011
Posts: 99
Hi All.

I'm playing around with casting between classes, i get the error: test.NewClass cannot be cast to test.NewClass1 when trying:





Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38363
    
  23
When do you get the error? At compile-time?
Did you think you can cast a NewClass object to NewClass1? You are telling the compiler you are certain it will be a NewClass1 and the compiler replies, “Don’t believe you!”
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14111
    
  16

Do you understand exactly what casting means?

When you cast an object, Java isn't automatically going to convert the object from some type to the type that you're casting it to. Casting only means that you tell the compiler: "I've got an object here, and I want you to treat it as if it is an object of type X". If, at runtime, the object that you're casting turns out to not really be an instance of class X, then you will get a ClassCastException.

In your example you have a superclass NewClass and a subclass NewClass1 (that extends NewClass). You create an instance of NewClass, and then you try to cast it to a NewClass1 object. That is not going to work, because a NewClass object is simply not a NewClass1 object.

Let's give the classes better names, then this will become more clear. Let's call the superclass Animal, and the subclass Dog. You are creating a new Animal, and then you're trying to cast that to a Dog. That obviously is not going to work, because an Animal is not always a Dog.

Keep in mind that inheritance in object oriented programming means specialization, which implies that there is an "is a" relationship going from the subclass to the superclass. In other words: a Dog is an Animal. But the other way around is not necessarily true: an Animal is not always a Dog, it could also be some other kind of animal.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Casting between classes.