Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Using "<? extends Interface>" vs Interface only [duplicate]

I have seen some code as follows

public interface IBean {

}

and its usage at some places as

public void persist(List<? extends IBean> beansList) {

}

However same can achieved with following code

public void persist(List<IBean> beansList) {

}

So what is the difference between both methods, both are excepting objects that must inherit IBean interface?

Here are the bean classes

public class Category implement IBean {
  //related fields
}

public class Product implement IBean {
  //related fields
}
like image 454
PHP Avenger Avatar asked Oct 19 '16 06:10

PHP Avenger


People also ask

What is the difference between extends and interfaces in Java?

The following table explains the difference between the extends and interface: 1. 2. It is not compulsory that subclass that extends a superclass override all the methods in a superclass. It is compulsory that class implementing an interface has to implement all the methods of that interface. 3. Only one superclass can be extended by a class. 4.

What is the difference between class and interface in Java?

Here, the ProgrammingLanguage class implements the interface and provides the implementation for the method. In Java, a class can also implement multiple interfaces. For example, Similar to classes, interfaces can extend other interfaces. The extends keyword is used for extending interfaces.

How to implement an interface in Java?

The interface includes an abstract method getName (). Here, the ProgrammingLanguage class implements the interface and provides the implementation for the method. In Java, a class can also implement multiple interfaces. For example, Similar to classes, interfaces can extend other interfaces.

Can We extend a class but not an interface?

We can extend a class but we cannot implement a class. We can implement an interface, but cannot extend an interface. In what cases should we be using extends? Show activity on this post. class ClassX extends ClassY { ... } interface InterfaceA extends InterfaceB { ... }


1 Answers

You can pass a List<Category> to public void persist(List<? extends IBean> beansList), but you cannot pass a List<Category> to public void persist(List<IBean> beansList).

On the other hand, you can pass a List<IBean> to both methods.

like image 66
Eran Avatar answered Nov 12 '22 11:11

Eran