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.
– user28595
But you are accessing the attribute of another instance, even though both are of the same class.
– Henrique Silva
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.
– user28595
https://stackoverflow.com/questions/17027139/access-private-field-of-another-object-in-same-class
– Piovezan
@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.
– Henrique Silva
Thanks for the replies @diegofm and Piovezan.
– Henrique Silva