Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java interface question

Let's say I have 2 interfaces, A and B:

public interface A {
 List<B> getBs();
}

public interface B {
}

and 2 classes that implement those interfaces:

public class AImpl implements A {

 public List<B> getBs() {
  return null;
 }

}


public class BImpl implements B {
}

Could it possible (maybe using generics) that my getter method returns a list of BImpl typed objects, something as:

public class AImpl implements A {

 public List<BImpl> getBs() {
  return null;
 }

}

Thanks

like image 414
luca Avatar asked Dec 17 '22 19:12

luca


1 Answers

I think you will need to change the interface declaration to this:

public interface A {
 List<? extends B> getBs();
}

However, if you want clients to know which implementation type you use, things will get more complicated:

public interface A<C extends B> {
     List<C> getBs();
}

public class AImpl implements A<Bimpl>{
     public List<Bimpl> getBs();
}
like image 142
Sean Patrick Floyd Avatar answered Jan 09 '23 02:01

Sean Patrick Floyd