Java Interface Question

Let's say I have two interfaces: A and B:

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

and 2 classes that implement these interfaces:

 public class AImpl implements A { public List<B> getBs() { return null; } } public class BImpl implements B { } 

Is it possible (possibly using generics) my getter method returns a list of typed BImpl objects, something like:

 public class AImpl implements A { public List<BImpl> getBs() { return null; } } 

thanks

+4
source share
3 answers

I think you will need to change the interface declaration:

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

However, if you want customers to know what type of implementation you are using, things get complicated:

 public interface A<C extends B> { List<C> getBs(); } public class AImpl implements A<Bimpl>{ public List<Bimpl> getBs(); } 
+6
source

Only if you can change the definition of the A.getBs() method to:

 List<? extends B> getBs(); 
+3
source

No, because generic types are not covariant.

List<BImpl> not a subclass of List<B> .

Part of the method contract in interface A is that it returns a List<B> .

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

A List<BImpl> does not support this contract. For example, a recipient expecting List<B> might try to add other types of B to the list instances β€” for example, BImpl2 and BImpl3 .

A List<B> containing only BImpl will support the contract.

+3
source

Source: https://habr.com/ru/post/1332977/


All Articles