Problem in conversion of class implementing list to the list type of interface

In the given task of todo’s where I have to create a list of candle ,
there’s a dilemma, that a interface can hold reference of class implementing it but the same is not valid for data structure like list, I am getting a constant error her
I have found on net this
//where dog is class implementing lAnimal
1.List animals = new List(dogs);// This type is not working

2.  List<Dog> dogs = new List<Dog>();
  List<IAnimal> animals = dogs;
  //Also this type is not working, I am getting error in both 

What else can I do. I have reffered the links in given in forum but didn’t understood how to get rid of this

You need to use it as List<Animal> = new ArrayList<Dog>()

Hope that helped without giving away the answer and spoiling the experience for you!

yep already did that way but still I am getting dog (as to what has been expected in module) getting underlined with the error read as
Type mismatch: cannot convert from ArrayList(dog) to List(IAnimal)
but while writting
IAnimal a = new dog();
I am getting no such error
@shoryajain @akashchhetri @AmoghaKS @Rahul-Crio.do

Yes you will get that, because type is mismatching as we can visualize you’re trying to match IAnimal with Dog. In list it doesn’t know what is the relationship between these two. It is just a declaration of variables nothing related to oops. So when you’re defining a list for Dog, It must be like
List<Dog> dog = new ArrayList<Dog>()

If you’re defining, List for animals it must be like
List<IAnimal> iAnimal = new ArrayList<IAnimal>()

Now, when you’re doing
IAnimal a= new Dog();

Here, using concept of oops in which you are making reference of interface and assigning it with object in which interface is implemented.

Now what to do?
make list of interface as I gave you above examples.

1 Like

List < Animal> = new ArrayList < Dog>();
I have made this but here I am getting type mismatch error
Type mismatch: cannot convert from ArrayList(dog) to List(IAnimal),
@akashchhetri

This is what I explained above in first half why you’re getting this error. :sweat_smile: If it’s not clear I will explain you more.

yes pleae do :(, because according to me it should work because according to your last point this should work
here IAnimal is interface and Dog class is implementing it
List < Dog> dogs = new ArrayList< Dog>();
List < IAnimal> animals = dogs;
as I can’t use new for interfaces
@akashchhetri

No, The way I did is just for a object of Dog I’m assigning to the reference of interface. Not passing list of object of dogs to the interface list.

1 Like

okay got it, now thank you :slight_smile:

1 Like

Now, you can do a new thing. Just create a list of reference first using a method I suggested then make another list of object and then individually add objects from the list of object in the list of reference.

Take a try if stuck somewhere will help you.

1 Like