A
A
Alex_java2016-04-26 12:51:22
Java
Alex_java, 2016-04-26 12:51:22

How to correctly override the equals method when inheriting?

Hello.
Did I understand correctly the implementation strategy of the equals method when inheriting classes (below is an implementation example)?

class A {
        int a = 1;

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (!(o instanceof A)) return false;

            A a1 = (A) o;

            return a == a1.a;

        }
    }

    class B extends A {
        int b = 1;

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;

            // Ошибка - нарушен принцип подстановки Барбары Лисков
            // if (o == null || getClass() != o.getClass()) return false;

            if (!(o instanceof A)) return false;
            if (!super.equals(o)) return false;

            if(o instanceof B) {
                B b1 = (B) o;
                return b == b1.b;
            }

            return true;
        }
    }

    @Test
    public void testEquals() {
        A a = new A();
        B b = new B();
        System.out.println(a.equals(b)); // true
        System.out.println(b.equals(a)); // true
    }

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
sirs, 2016-04-26
@sirs

A controversial issue, but Josh Bloch agrees with you .
On the other hand, the equals symmetry principle is violated.
In any case, there is no silver bullet, and individual solutions are great on a case-by-case basis.

Y
YV, 2016-04-26
@targetjump

In principle, the idea is correct, you can make it a little more beautiful

//..
if (!(o instanceof A) {
    return false;
}
if (!(o instanceof B)) {
    return this.equals(o);
}
//..

There is no right way because you will always violate something (transitivity in this case).
From Effective Java 2nd edition item8:
Often you can just rethink your approach and use composition instead of inheritance.

1
1Michael1, 2015-05-08
@1Michael1

you definitely need to start from the very beginning...
add to the beginning of the script:
error_reporting(E_ALL);
and then parse the errors that lie around.

E
Evgeny Lavrentiev, 2015-05-09
@lavrentiev

In short, this is a robot, and now what I saw looking at the code.
In your HTML, when you iterate over the $pages array, in your case, as I understand it, start_points and startpage are empty, and also take out your start and end points from foreach, IMHO there will be duplicates. Actually, what am I saying that your empty links are empty duplicates of start and end points and startpage and endpage.
Turn on the display of errors and see if I don’t know there, for example, your array through print_r.
In general, of course, bad, but good luck with the study.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question