Pessoal, mais uma dúvida para tirar com vocês! rsrs
Estou fazendo o seguinte exercício sobre Variáveis e acabou aparecendo uma dúvida sobre o for:
Este é o código:
public class CountInstances {
private static int numInstances = 0;
protected static int getNumInstances(){
return numInstances;
}
private static void addInstance(){
numInstances++;
}
CountInstances(){
CountInstances.addInstance();
}
public static void main(String[] args) {
System.out.println("Starting with "+ CountInstances.getNumInstances() + " intances");
for (int i=0; i<10; i++)
new CountInstances();
System.out.println("Created "+ CountInstances.getNumInstances() + " intances");
}
}
Quando rodo esse programa sem as chaves no for ele me gera isso:
Starting with 0 intances
Created 10 intances
Agora, quando rodo com as chave no for, ou seja, assim:
public class CountInstances {
private static int numInstances = 0;
protected static int getNumInstances(){
return numInstances;
}
private static void addInstance(){
numInstances++;
}
CountInstances(){
CountInstances.addInstance();
}
public static void main(String[] args) {
System.out.println("Starting with "+ CountInstances.getNumInstances() + " intances");
for (int i=0; i<10; i++){
new CountInstances();
System.out.println("Created "+ CountInstances.getNumInstances() + " intances");
}
}
}
Ele apresenta todas as instâncias criadas:
Starting with 0 intances
Created 1 intances
Created 2 intances
Created 3 intances
Created 4 intances
Created 5 intances
Created 6 intances
Created 7 intances
Created 8 intances
Created 9 intances
Created 10 intances
Por que sem as chaves, o JAVA omite?
Abraços!