靜態嵌套類(Static Nested Class)和內部類(Inner Class)的不一樣?

Static Nested Class是被聲明爲靜態(static)的內部類,它能夠不依賴於外部類實例被實例化。而一般的內部類須要在外部類實例化後才能實例化,其語法看起來挺詭異的,以下所示。java

/**
  * 撲克類(一副撲克)
  * @author 駱昊
  *
  */
public class Poker {
     private static String[] suites = { "黑桃" , "紅桃" , "草花" , "方塊" };
     private static int [] faces = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 };
 
     private Card[] cards;
 
     /**
      * 構造器
      *
      */
     public Poker() {
         cards = new Card[ 52 ];
         for ( int i = 0 ; i < suites.length; i++) {
             for ( int j = 0 ; j < faces.length; j++) {
                 cards[i * 13 + j] = new Card(suites[i], faces[j]);
             }
         }
     }
 
     /**
      * 洗牌 (隨機亂序)
      *
      */
     public void shuffle() {
         for ( int i = 0 , len = cards.length; i < len; i++) {
             int index = ( int ) (Math.random() * len);
             Card temp = cards[index];
             cards[index] = cards[i];
             cards[i] = temp;
         }
     }
 
     /**
      * 發牌
      * @param index 發牌的位置
      *
      */
     public Card deal( int index) {
         return cards[index];
     }
 
     /**
      * 卡片類(一張撲克)
      * [內部類]
      * @author 駱昊
      *
      */
     public class Card {
         private String suite;   // 花色
         private int face;       // 點數
 
         public Card(String suite, int face) {
             this .suite = suite;
             this .face = face;
         }
 
         @Override
         public String toString() {
             String faceStr = "" ;
             switch (face) {
             case 1 : faceStr = "A" ; break ;
             case 11 : faceStr = "J" ; break ;
             case 12 : faceStr = "Q" ; break ;
             case 13 : faceStr = "K" ; break ;
             default : faceStr = String.valueOf(face);
             }
             return suite + faceStr;
         }
     }
}

測試代碼:dom

 
class PokerTest {
 
     public static void main(String[] args) {
         Poker poker = new Poker();
         poker.shuffle();                // 洗牌
         Poker.Card c1 = poker.deal( 0 );  // 發第一張牌
         // 對於非靜態內部類Card
         // 只有經過其外部類Poker對象才能建立Card對象
         Poker.Card c2 = poker. new Card( "紅心" , 1 );    // 本身建立一張牌
 
         System.out.println(c1);     // 洗牌後的第一張
         System.out.println(c2);     // 打印: 紅心A
     }
}
相關文章
相關標籤/搜索