Converting Parent Instance to child Instance

I've Parent and child(extends Parent) class To initialize the constructors, I'm injecting from google.juice#injector. Let me show the code,

Parent.class

Child.class

When I do this, ClassCastException is happening. Why is it so? Is there any way to convert instance of parent to child instance.

Thanks:
Ramakrishna K.C

Ulf Dittmer

Rancher

Posts: 42972

73

posted 3 years ago

First off, no "conversion" is happening - it's called a cast. Just to keep the terminology straight :-)

What are the relationships between the Dog, Animal and Child classes? Child would need to extend Animal (directly or indirectly) for that cast to work. And Child would need to extend Dog (directly or indirectly) for the assignment to the "dog" variable to work.

Ulf Dittmer

Rancher

Posts: 42972

73

posted 3 years ago

OK, now that you have edited the post my previous reply no longer makes sense. The question would instead be:

What is the relationship between the Dog and Animal classes? Dog would need to extend Animal (directly or indirectly) for that cast (and the subsequent assignment) to work.

Ramakrishna Udupa

Ranch Hand

Posts: 254

posted 3 years ago

Actually I want an instance of Dog in my child class. No relation-ships to Dog, Animal to child class. But, Dog is an Animal. So, parent-child relation-ship between Dog and Animal. Also,

Animal.class

Dog.class

Ulf Dittmer

Rancher

Posts: 42972

73

posted 3 years ago

I'm confused. "Dog is an Animal" and "public class Dog {" (without an "extends Animal") directly contradict one another. Which is it? If the latter, then you can not assign an instance of Animal to a variable of type Dog.

Ramakrishna Udupa

Ranch Hand

Posts: 254

posted 3 years ago

@Ulf Dittmer Nope. When I cast That its giving me classcast exception.

When I do this, ClassCastException is happening. Why is it so? Is there any way to convert instance of parent to child instance.

The only cast in the code that you showed us, is in line 8 of the Child class. Unfortunately, we can't tell exact what was passed to the Child class, to be able to answer your question. You need to show us the code that instantiates the Child instance.