淺析Java語言中的內部類

來源:互聯網
上載者:User

提起Java內部類(Inner Class)可能很多人不太熟悉,實際上類似的概念在 C++裡也有,那就是嵌套類(Nested Class),關於這兩者的區別與聯絡,在下 文中會有對比。內部類從表面上看,就是在類中又定義了一個類(下文會看到, 內部類可以在很多地方定義),而實際上並沒有那麼簡單,乍看上去內部類似乎 有些多餘,它的用處對於初學者來說可能並不是那麼顯著,但是隨著對它的深入 瞭解,你會發現Java的設計者在內部類身上的確是用心良苦。學會使用內部類,是掌握Java進階編程的一部分,它可以讓你更優雅地設計你的程式結構。下面從 以下幾個方面來介紹:

第一次見面

public interface Contents {
  int value();
}
public interface Destination {
  String readLabel();
}
public class Goods {
  private class Content implements Contents {
   private int i = 11;
   public int value() {
    return i;
   }
  }
  protected class GDestination implements Destination {
   private String label;
   private GDestination(String whereTo) {
    label = whereTo;
   }
   public String readLabel() {
    return label;
   }
  }
  public Destination dest(String s) {
   return new GDestination(s);
  }
  public Contents cont() {
   return new Content();
  }
}
class TestGoods {
  public static void main(String[] args) {
   Goods p = new Goods();
   Contents c = p.cont();
   Destination d = p.dest("Beijing");
  }
}

在這個例子裡類Content和GDestination被定義在了類Goods內部,並且分別 有著protected和private修飾符來控制存取層級。Content代表著Goods的內容, 而GDestination代表著Goods的目的地。它們分別實現了兩個介面Content和 Destination。在後面的main方法裡,直接用 Contents c和Destination d進行 操作,你甚至連這兩個內部類的名字都沒有看見!這樣,內部類的第一個好處就 體現出來了——隱藏你不想讓別人知道的操作,也即封裝性。

同時,我們也發現了在外部類作用範圍之外得到內部類對象的第一個方法, 那就是利用其外部類的方法建立並返回。上例中的cont()和dest()方法就是這麼 做的。那麼還有沒有別的方法呢?當然有,其文法格式如下:

outerObject=new outerClass(Constructor Parameters);
outerClass.innerClass innerObject=outerObject.new InnerClass (Constructor Parameters);

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.