hamed
hamed

Reputation: 8033

java - can not cast to child class

I have two entity in this structure:

class Parent{
   public int type;
   //Setters and getters
}

class Child1 extends Parent{

}

I have an instance of Parent and I want to cast it to Child1 based on condition in this way:

Parent parent = ...
if(parent.getType() == 1)
    Child1 child = (Child1) parent;

But it gives me ClassCastException. How can I resolve this problem? What's is the best way to use downcasting in java?

Upvotes: 0

Views: 1094

Answers (5)

Mauran
Mauran

Reputation: 141

you haven't create object properly , create object like this Parent child= new Child1();

Upvotes: 0

Thomas Stets
Thomas Stets

Reputation: 3035

A cast to a child class is only possible if the object already is of that type.

A cast of an object does not change the object ot the class of an object. It just tells the compiler "this object actually is an instance of the child class, use it as such". (Casts of primitive types are different, they actually change the type of the value!)

In your code sample you don't show how the parent object is created, so I don't know whether this is really the problem. Perhaps you can add the missing code to make that clear.

Upvotes: 1

Null Pointer
Null Pointer

Reputation: 140

You need to use :

Parent parent = new Child1();

Upvotes: 0

SacJn
SacJn

Reputation: 777

Can you cast Animal class to Dog class ? Even though you know there are many more examples of Animals. Its just Dog is one type of animal thats why you can cast it to Animal but Dog is not the animal.

Upvotes: 0

Abimaran Kugathasan
Abimaran Kugathasan

Reputation: 32468

You can't cast a parent type object into child type object. You have misunderstod the inheritance behaviour.

Upvotes: 2

Related Questions