Home > Java > javaTutorial > Compatibility rules for Java function generics

Compatibility rules for Java function generics

王林
Release: 2024-04-26 18:03:01
Original
667 people have browsed it

The compatibility rules of Java function generics ensure type safety. Rules include: same type parameter lists, same type parameter bounds, and contravariant and covariant type parameters. For example, <List<Cat>> is compatible with <List<Animal>> (contravariant), while <String> is compatible with <Object> (covariant).

Java 函数泛型的兼容性规则

Compatibility rules for Java function generics

Java generic functions allow us to write code in a type-safe manner, But not following the correct compatibility rules can lead to compile-time errors. Let’s sort out the rules to avoid such problems.

Rule 1: The type parameter lists are the same

Only function types with the same parameter list are compatible. So the following example will result in an error:

public <T> void func1(T v) {}
public <U> void func2(U v) {}
Copy after login

Rule 2: Type parameters have the same bounds

Bounds define the allowed values ​​of a generic type. Functions are incompatible if they have different bounds for parameters of the same type. For example:

public <T extends Comparable<T>> void func1(T v) {}
public <T extends Number> void func2(T v) {}
Copy after login

Rule 3: Contravariant and covariant type parameters

  • Contravariance: If subclass type T can replace superclass type S, then <T> is type compatible with <S>. For example, <List<Cat>> is compatible with <List<Animal>>.
  • Covariance: If the superclass type T can replace the subclass type S, then the <S> type is compatible with <T>. For example, <String> is compatible with <Object>.

Practical case

Consider the following code:

public <T extends Animal> void func1(T t) {
    // 代码...
}

public void func2(Cat c) {
    // 代码...
}
Copy after login

func1 Expects an Animal or an instance of its subclass. func2 Expects a Cat instance. Since Cat extends Animal, func1 is compatible with func2 and can receive Cat type parameters.

Conclusion

It is crucial to follow the compatibility rules for function generics to avoid compile-time errors and ensure type safety.

The above is the detailed content of Compatibility rules for Java function generics. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template