Porównywanie własnych obiektów

package pl.am.object2.lesson37;

public class PorownywanieObiektow {
    public static void main(String[] args) {
        Prostokat prostokat1 = new Prostokat(2, 3);
        Prostokat prostokat2 = new Prostokat(2, 3);

        Kwadrat kwadrat1 = new Kwadrat(6);
        Kwadrat kwadrat2 = new Kwadrat(6);

        Prostokat prostokat3 = prostokat1;

        Trojkat trojkat = new Trojkat();

        System.out.println(prostokat1 == prostokat2);
        System.out.println(prostokat1 == prostokat3);
        System.out.println(prostokat1.equals(prostokat2));
        System.out.println(prostokat1.equals(trojkat));
        System.out.println(kwadrat1.equals(kwadrat2));
    }
}
package pl.am.object2.lesson37;

public class Figura {
}
package pl.am.object2.lesson37;

public class Trojkat extends Figura {
}
package pl.am.object2.lesson37;

import java.util.Objects;

public class Prostokat extends Figura {
    protected final double a;
    protected final double b;

    public Prostokat(double a, double b) {
        this.a = a;
        this.b = b;
    }

    public double getA() {
        return a;
    }

    public double getB() {
        return b;
    }

    public double obliczPole() {
        return a * b;
    }

    public double obliczObwod() {
        return 2*a + 2*b;
    }


    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Prostokat prostokat = (Prostokat) o;
        return Double.compare(prostokat.a, a) == 0 &&
                Double.compare(prostokat.b, b) == 0;
    }

    @Override
    public int hashCode() {
        return Objects.hash(a, b);
    }

    @Override
    public String toString() {
        return "Prostokat{" +
                "a=" + a +
                ", b=" + b +
                ", pole=" + obliczPole() +
                ", obwód=" + obliczObwod() +
                '}';
    }
}
package pl.am.object2.lesson37;

public class Kwadrat extends Prostokat {

    public Kwadrat(double bok) {
        super(bok, bok);
    }

    public double getBok() {
        return a;
    }

    @Override
    public String toString() {
        return "Kwadrat{" +
                "bok=" + a +
                ", pole=" + obliczPole() +
                ", obwód=" + obliczObwod() +
                '}';
    }
}

Dodaj komentarz

Twój adres e-mail nie zostanie opublikowany. Wymagane pola są oznaczone *