從頭認識java-8.1 內部類

來源:互聯網
上載者:User

從頭認識java-8.1 內部類

這一章節我們來討論一下內部類。

1.概念

在類的內部建立的類就是內部類。

 

package com.ray.ch08;public class Test {class Destination {}class Content {}}

上面的Destination和Content就是內部類。

 

 

2.為什麼需要內部類?

(1)隱藏代碼

 

package com.ray.ch08;import com.ray.ch08.Test.Destination;public class Test {class Destination {}private class Content {}}class Ship {// Content content = new Test().new Content();//error}

我們可以使用private來隱藏某些實作類別。

 

當我們需要調用某個類的內部類時,必須先new 外部類,就像下面的Destination類一樣。

 

package com.ray.ch08;import com.ray.ch08.Test.Destination;public class Test {class Destination {}private class Content {}}class Ship {Destination destination = new Test().new Destination();// Content content = new Test().new Content();//error}


 

(2)通過與外部類的通訊

 

package com.ray.ch08;public class Test {private int id = 0;class Destination {private void print() {System.out.println(id);// 這裡的id是int com.ray.ch08.Test.id}}private class Content {}}

上面的代碼示範了內部類可以改變外部類的屬性域,這裡可以衍生很多變化,在後面會詳細展開。

 

 

(3)代碼更加優雅

這一點就不用代碼示範,因為根據不同的需求要求各不相同。

 

總結:這一章節主要講述了內部類的概念與使用的原因。

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.