How to solve "Design For Extension" Warning CheckStyle on hashCode and equal

Given:

public class Foo {

    @Override
    public boolean equals(final Object obj) {
        // implementation
    }

    @Override
    public int hashCode() {
        // implementation
    }
}

and

public class Bar extends Foo {

    @Override
    public boolean equals(final Object obj) {
        // different implementation
    }

    @Override
    public int hashCode() {
        // different implementation
    }
}

I understand why Checkstyle gives me β€œDesign for extension: the hashCode method” is not intended to be extended - it must be abstract, final or empty. ”The method is neither final, nor abstract, nor empty. But how else can I achieve this, but not violate any rules or guidelines of the TOE? For example, where will it be used:

Foo (for brevity, I used the default implementation of Object)

public class Foo {

    public int getX() {
        return x;
    }

    public void setX(final int x) {
        this.x = x;
    }

    @Override
    public int hashCode() {
        return super.hashCode();
    }

    @Override
    public boolean equals(final Object obj) {
        return super.equals(obj);
    }

    private int x;
}
public class Bar extends Foo {

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = result * prime + getX();
        return result;
    }

    @Override
    public boolean equals(final Object obj) {
        if (obj == null) {
            return false;
        }
        if (obj == this) {
            return true;
        }
        if (!(obj instanceof Bar)) {
            return false;
        }
        final Bar bar = (Bar) obj;
        if (bar.getX() != this.getX()) {
            return false;
        }
        return true;
    }
}
public static void main(final String[] args) {
    final Bar barOne = new Bar();
    barOne.setX(1);
    final Bar barTwo = new Bar();
    barTwo.setX(1);
    final Map<Bar, String> barMap = new HashMap<>();
    barMap.put(barOne, null);
    barMap.put(barTwo, null);
    System.out.println(barMap.size());

    final Foo fooOne = new Foo();
    fooOne.setX(1);
    final Foo fooTwo = new Foo();
    fooTwo.setX(1);
    final Map<Foo, String> fooMap = new HashMap<>();
    fooMap.put(fooOne, null);
    fooMap.put(fooTwo, null);
    System.out.println(fooMap.size());
}

Outputs

1
2

, , Map , -. Object Object (Foo) (). Bar x. , , hashCode .

, , Foo Bar ?

+4
3

, OO, Java.

, , , , - , (, java.lang.Object ), , , .

hashcode/equals OO, . , , , , , .

, item 8 Java. (. . 38):

, OO.

, , Sun, Java. , "" Java .

+4

.

  • a, b c.

  • a.equals(b) a.equals(c). b.equals(c).

  • a - Base; b c Derived.

Derived#equals, . , , Base.

, relatioships : a b, c, b c. equals , , Base Derived.

hashCode(), - , hashCode equals, .

+2

, , . . IMO, , , , hashcode/equals . , , , , ( ) . , . , , OCP LSP. .

0

All Articles