All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.java.rules.java.S2638.html Maven / Gradle / Ivy

There is a newer version: 8.6.0.37351
Show newest version

This rule raises an issue when an overriding method changes a contract defined in a superclass.

Why is this an issue?

Because a subclass instance may be cast to and treated as an instance of the superclass, overriding methods should uphold the aspects of the superclass contract that relate to the Liskov Substitution Principle. Specifically, if the parameters or return type of the superclass method are marked with any of the following: @Nullable, @CheckForNull, @NotNull, @NonNull, and @Nonnull, then subclass parameters are not allowed to tighten the contract, and return values are not allowed to loosen it.

Code examples

Noncompliant code example

public class Fruit {

  private Season ripe;
  private String color;

  public void setRipe(@Nullable Season ripe) {
    this.ripe = ripe;
  }

  public @NotNull Integer getProtein() {
    return 12;
  }
}

public class Raspberry extends Fruit {

  public void setRipe(@NotNull Season ripe) {  // Noncompliant: the ripe argument annotated as @Nullable in parent class
    this.ripe = ripe;
  }

  public @Nullable Integer getProtein() {  // Noncompliant: the return type annotated as @NotNull in parent class
    return null;
  }
}

Compliant solution

public class Fruit {

  private Season ripe;
  private String color;

  public void setRipe(@Nullable Season ripe) {
    this.ripe = ripe;
  }

  public @NotNull Integer getProtein() {
    return 12;
  }
}

public class Raspberry extends Fruit {

  public void setRipe(@Nullable Season ripe) {
    this.ripe = ripe;
  }

  public @NotNull Integer getProtein() {
    return 12;
  }
}

Resources

Documentation





© 2015 - 2024 Weber Informatics LLC | Privacy Policy