Home > Java > javaTutorial > Why is \'extends T\' allowed for type parameter bounds in Java, but not \'implements T\'?

Why is \'extends T\' allowed for type parameter bounds in Java, but not \'implements T\'?

Barbara Streisand
Release: 2024-11-02 06:25:29
Original
981 people have browsed it

Why is

Extends vs. Implements in Generic Type Parameter Bounds

Question:

In Java, why is "extends T" permitted for defining type parameter bounds, but "implements T" is not allowed?

For instance, the following code is prohibited:

<code class="java">public interface C {}
public class A<B implements C> {}</code>
Copy after login

While this code is valid:

<code class="java">public class A<B extends C> {}</code>
Copy after login

Answer:

Semantically, there is no distinction between "extends" and "implements" within the generic constraint language. The constraint possibilities are limited to "extends" and "super," reflecting the direction of inheritance or assignment compatibility.

  • extends T: The class associated with the type parameter can be assigned to or extended from the type T.
  • super T: The class associated with the type parameter can be assigned from the type T.

In the case of the invalid code example, it attempts to use "implements" to define a constraint on the type parameter B. However, "implements" is not a valid constraint type and is therefore not permitted.

The above is the detailed content of Why is \'extends T\' allowed for type parameter bounds in Java, but not \'implements T\'?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template