-1

Assuming that IUncle is an interface that Uncle implement. Assumming that I don't wont to use concrete classes inside the class Child because I want Child to be use with any implementation of Iuncle. How can I change the implementation of Child (below) in the way that will work for any implemtation of Uncle.

public class Child {

private List<IUncle> uncles;

public Child(List<IUncle> uncles){
    this.uncles = uncles;
}

public void addUncle(IUncle uncle) {
    this.uncles.add(uncle);
}

}

In the main class, I use this class like this:

List<Uncle> uncles = new ArrayList<Uncle>();
Child oneChild  = new Child(uncles);
oneChild.addUncle(new Uncle);

This is doesn't work at all !!!

Please, can someone give the proper way to deal with this situation in java ?

mokolop
  • 11
  • 1
  • 3
  • `List` and `List` are incompatible. They don't store the same thing. – Andreas Aug 12 '16 at 00:37
  • What is `Uncle` and what is `IUncle`? – user1803551 Aug 12 '16 at 04:22
  • IUncle is in fact an interface and Uncle is a class implementing that interface. And yes, I know that List and List are incompatible. The question is how to manage turn this class in the way that respect the "O" of SOLID principle by not using the concrete class inside an implementation. – mokolop Aug 12 '16 at 05:51

2 Answers2

0

You have a syntax error, I am not sure what your Uncle class looks like, but try

oneChild.addUncle(new Uncle ());

You specified a method for adding an Uncle but you did not use it.

Also, I think you are confusing your IUncle interface (??) with your Object Uncle. They are not the same thing and are not interchangeable.

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
  • 1
    Since you want to answer about compile errors, do you want to expand your answer to also explain why `List` and `List` are incompatible, i.e. why `new Child(uncles)` won't compile, even if `Uncle implements IUncle`? – Andreas Aug 12 '16 at 00:39
  • @Andreas I am at a loss how to explain this as I am not sure what `IUncle` is - probably an interface, but I am not sure. – Scary Wombat Aug 12 '16 at 00:42
  • IUncle is an interface and, Uncle implement that interface. – mokolop Aug 12 '16 at 05:54
0

One of my manager in my previous came with an answer. It was quite simple!

In fact, there is nothing going wrong in the child class. The issue is in the main class. Which, should look like this :

List<IUncle> uncles = new ArrayList<IUncle>();
Child oneChild  = new Child(uncles);
oneChild.addUncle(new Uncle);

Thanks !

mokolop
  • 11
  • 1
  • 3