Olá a todos… Neste tópico http://www.guj.com.br/posts/list/39369.java um amigo disse que o bloco static é executado antes do construtor, baseado nisso posso afirmar que o bloco static é executado antes do bloco de instância?
Vejam neste código que representa uma carteada de baralho:
Classe Card:
package teste;
import java.util.ArrayList;
import java.util.List;
public class Card {
public enum Rank { AS, DOIS, TRES, QUATRO, CINCO, SEIS,
SETE, OITO, NOVE, DEZ, VALETE, DAMA, REI}
public enum Suit { PAUS, OURO, COPAS, ESPADAS }
private final Rank rank;
private final Suit suit;
private Card(Rank rank, Suit suit) {
this.rank = rank;
this.suit = suit;
}
{
System.out.println("Instância!");
}
public Rank getRank() {
return rank;
}
public Suit getSuit() {
return suit;
}
public String toString() {
return rank + " de " + suit + "\n";
}
private static final List<Card> protoDeck = new ArrayList<Card>();
// Initialize prototype deck
static {
for (Suit suit : Suit.values())
for (Rank rank : Rank.values())
protoDeck.add(new Card(rank, suit));
System.out.println("Classe!");
}
public static ArrayList<Card> newDeck() {
// Return copy of prototype deck
return new ArrayList<Card>(protoDeck);
}
}
Classe Deal:
package teste;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Deal {
public static void main(String args[]) {
int numHands = Integer.parseInt("1");
int cardsPerHand = Integer.parseInt("5");
List<Card> deck = Card.newDeck();
Collections.shuffle(deck);
for (int i=0; i < numHands; i++)
System.out.println(deal(deck, cardsPerHand));
}
public static ArrayList<Card> deal(List<Card> deck, int n) {
int deckSize = deck.size();
List<Card> handView = deck.subList(deckSize-n, deckSize);
ArrayList<Card> hand = new ArrayList<Card>(handView);
handView.clear();
return hand;
}
}
O resultado em ordem de impressão é:
- 52 saídas de strings “Instância”;
- 1 saída de string “Classe”;
- 5 strings representado a “mão” do jogo;
Observando o resultado nota-se que o bloco de instância foi executado primeiro ou pelo menos sua saída foi feita antes do bloco static, é isso mesmo, o bloco static é executado depois?
Abraço…