Comparison Methodthe Comparable interface allows encapsulation breaking?

Asked

Viewed 117 times

1

The Student class has its private attributes and to access or modify them it is necessary to use the get and set methods. In addition, the Student class implements the Comparable interface.

class Estudante implements Comparable<Estudante> {

    private String nome;
    private double nota;

    public Estudante(String nome, double nota) {
        this.nome = nome;
        this.nota = nota;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public double getNota() {
        return nota;
    }

    public void setNota(double nota) {
        this.nota = nota;
    }

    @Override
    public int compareTo(Estudante o) {
        o.nome = "QUEBRA DE ENCAPSULAMENTO";
        return (int) (this.nota - o.getNota());
    }
}

In the main method of the main class Testeuniversity are instantiated 2 objects of the class Student and the getName method of the object E2 is called before and after the comparison of E1 with E2.

Why it is possible to break the encapsulation of the E2 name attribute within the E1 compareTo method?

Behold: https://ideone.com/9H5pna

  • But who is accessing the field is own class, breaking encapsulation is when a field is accessible to the outside in an unrestricted way.

  • But you are accessing the attribute of another instance, even though both are of the same class.

  • They are two instances of the same class, may not be the same object but both know the implementation of the other, there is no violation in this case.

  • 1
  • @Piovezan After reading the answers of the link above I understood the advantages of private fields having access to class level and not object level.

  • Thanks for the replies @diegofm and Piovezan.

Show 1 more comment
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.