The attribute cursos
is the type String[]
and is declared with the modifier private
. This means it is accessible only from within the class Aluno
.
However, you may need to access it from an instance created from the respective class. Because of this, it is very common to use methods to make this possible. Gets
and Sets
is a widely used nomenclature (mainly in Java) to refer to methods that allow you to obtain and change the content of a private attribute.
Therefore, the method getCursos()
does nothing more than return the attribute cursos
. Already the setCursos()
, allows you to change the attribute cursos
.
Example of the use of get
and set
:
public static void main(String[] args) {
Aluno aluno = new Aluno();
//Utilizando o getCursos() para poder alterar o conteúdo do vetor
aluno.getCursos()[0] = "Curso0";
aluno.getCursos()[1] = "Curso1";
aluno.getCursos()[2] = "Curso2";
aluno.getCursos()[3] = "Curso3";
aluno.getCursos()[4] = "Curso4";
String[] novosCursos = new String[10];
for(int i = 0; i < novosCursos.length; i++)
novosCursos[i] = "Curso" + i;
//Utilizando o set para alterar o atributo alunos, passando
//a referencia de um novo vetor criado acima
aluno.setCursos(novosCursos);
}
Note that it would not be possible to access the attribute cursos
from the instance aluno
created above, if there were no method getCursos()
.
I still can’t understand...why you used get and not set?
student.getCursos()[0] = "Courses0"; ?
The doubt above was made in a comment and I found very pertinent, because really when we are learning there can be this confusion.
The method setCursos
does not change the content of a given vector position, as you might suggest. In other words, the set
, although it means changing something, in this case, nay is the content of a specific position.
What the set
is to change the attribute reference cursos
class Student (knowing a little pointer can help you understand this more easily).
Change the reference means the following:
When a new Aluno
is created with new Aluno()
a vector of 5 positions of the type String
is allocated and the reference of that vector in memory is stored by the attribute cursos
.
When using the setCursos()
, changes the reference stored by the attribute cursos
. Therefore, the attribute cursos
that was referencing a 5-position vector in memory, is now referencing another vector, in the case of the above example, a 10-position vector.
Already the method getCursos()
is used to gain access to the vector cursos
(note that it only returns the vector cursos
). Having access to the vector means being able to manipulate it (change the content of the positions), access its methods (such as length).
Because of this, to change or access a vector position is done getCursos()[i]
. Note that if the attribute cursos
were public
, then it could be done aluno.cursos[i]
.
Related question: Why use get and set in Java?
Could you add the code snippets that you refer to, please?
– cantoni