N
N
nolouds2021-12-14 11:03:30
Spring
nolouds, 2021-12-14 11:03:30

Why is Override used in this code (from the Spring tutorial)?

There are three overridden equals, hashCode, toString methods. Why is an annotation written for them, if there is only one class, it does not have a parent class and similar methods? As far as I understand from the explanations on the Internet, "@Override" is written to the methods that the parent class also has. And why is it written "Employee() {}" before creating a method with this name?

package payroll;

import java.util.Objects;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
class Employee {

  private @Id @GeneratedValue Long id;
  private String name;
  private String role;

  Employee() {}

  Employee(String name, String role) {

    this.name = name;
    this.role = role;
  }

  public Long getId() {
    return this.id;
  }

  public String getName() {
    return this.name;
  }

  public String getRole() {
    return this.role;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public void setName(String name) {
    this.name = name;
  }

  public void setRole(String role) {
    this.role = role;
  }

  @Override
  public boolean equals(Object o) {

    if (this == o)
      return true;
    if (!(o instanceof Employee))
      return false;
    Employee employee = (Employee) o;
    return Objects.equals(this.id, employee.id) && Objects.equals(this.name, employee.name)
        && Objects.equals(this.role, employee.role);
  }

  @Override
  public int hashCode() {
    return Objects.hash(this.id, this.name, this.role);
  }

  @Override
  public String toString() {
    return "Employee{" + "id=" + this.id + ", name='" + this.name + '\'' + ", role='" + this.role + '\'' + '}';
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Сергей Горностаев, 2021-12-14
@nolouds

Обожемой, это же основы Java, рано вам ещё в Spring лезть.

Почему пишется аннотация к ним, если класс только один, у него нет родительского класса и похожих методов?

Все классы неявно наследуют Object, в котором и определены интересующие вас методы.
И почему пишется "Employee() {}" до создания метода c этим именем?

Во-первых, это не метод, а конструктор. Во-вторых, у сущностей должен быть конструктор без параметров, иначе ORM не сможет их создавать.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question