luca
luca

Reputation: 75

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

Upvotes: 4

Views: 273

Answers (3)

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 299048

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();
}

Upvotes: 6

Andy Thomas
Andy Thomas

Reputation: 86459

No, because generic types are not covariant.

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

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

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

A List<BImpl> does not support that contract. For example, a recipient expecting a List<B> might try to add to the list instances of other types of B -- say, BImpl2 and BImpl3.

A List<B> containing only BImpl's would support the contract.

Upvotes: 3

OscarRyz
OscarRyz

Reputation: 199264

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

List<? extends B> getBs();

Upvotes: 2

Related Questions