File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Casting between classes." Watch "Casting between classes." New topic

Casting between classes.

Rob Brew
Ranch Hand

Joined: Jun 23, 2011
Posts: 101
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

Joined: Oct 13, 2005
Posts: 46435
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: 15101

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 8 API documentation
I agree. Here's the link:
subject: Casting between classes.
It's not a secret anymore!