I'm playing around with casting between classes, i get the error: test.NewClass cannot be cast to test.NewClass1 when trying:
Joined: Oct 13, 2005
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!”
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.