7
I built two simple classes:
import java.util.ArrayList;
import java.util.List;
public class Aluna {
String nome;
String idade;
String cpf;
List<Aluna> listar(){
ArrayList<Aluna> aluns = new ArrayList<>();
Aluna aluna;
aluna = new Aluna();
aluna.cpf="839457476";
aluna.idade="30";
aluna.nome="Tereza ";
aluns.add(aluna);
aluna = new Aluna();
aluna.cpf="89437298472";
aluna.idade="17";
aluna.nome="Aline";
aluns.add(aluna);
return aluns;
}
}
public class Start {
public static void main(String[] args) {
for(Aluna al : new Aluna().listar()){
System.out.println(al.cpf);
System.out.println(al.idade);
System.out.println(al.nome);
System.out.println("------------------------");
}
}
}
I was left with doubt of the excerpt in the code:
for(Aluna al : new Aluna().listar()){
I know it’s a foreach and it lists data. But instantiating a class and having access to its method right in the class within the foreach I found strange. How could they do that kind of thing?
Ps.:Do not take into account the lack of encapsulation.
What kind of thing? Make a method call? I didn’t quite understand the doubt.
– user28595