[問題] static inner class

看板java作者 (奇奇)時間7年前 (2017/10/14 04:05), 編輯推噓2(2017)
留言19則, 4人參與, 7年前最新討論串1/1
之前寫一些程式的時候,碰到需要獨立出一個類別的東西 往往都獨立初放在另一個檔案,放在同一個package裡面 這次把這些slave class移放到主要的class裡面變成inner class 就碰到了這個問題: inner class到底要不要宣告為static google一番後大致有了個了解 知道static與nonstatic inner class在使用外部class成員資格上的限制 以及本身可以創建的變數種類等等 但我還是有點困惑 主要是因為以前學static variable, method的時候 我們都知道static variable, method是在整個主程式底下只會有一份的 也就是不會因為所屬的class instance不同而改變 最常舉的例子就是圓周率 但static class就讓我有點困惑的是 雖然他是靜態的,但是可以instantiated 這個static是不是和variable以及method的static不太一樣? -- ● 日本的驕傲 乒乓球放在上面也不會滾 * 中華民國 很屌嗎,我們台灣 動,馬路就是這麼平! 的驕傲 也可以。 \● / ● / ︱> #1FPWIVQQ (joke) <︱> ● /\ ▄▃▂▄ ▂▄●▃ /\▂▃ ███████████████ψ FallRed ██████████████ -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 123.193.233.18 ※ 文章網址: https://www.ptt.cc/bbs/java/M.1507925102.A.DFE.html

10/14 07:08, 7年前 , 1F
意思上不太一樣。簡單一句,inner class 能static 就s
10/14 07:08, 1F

10/14 07:08, 7年前 , 2F
tatic
10/14 07:08, 2F

10/14 10:05, 7年前 , 3F
static/nonstatic inner class的最大差別是在nonstatic
10/14 10:05, 3F

10/14 10:05, 7年前 , 4F
inner class的instance一定要綁定一個外層class的instance
10/14 10:05, 4F

10/14 10:06, 7年前 , 5F
使用外部成員的限制只是因為這點造成的自然結果
10/14 10:06, 5F

10/14 10:16, 7年前 , 6F
這跟nonstatic method裡有this可以用一樣,nonstatic inner
10/14 10:16, 6F

10/14 10:18, 7年前 , 7F
class中可使用outer class的this,但相對的new的時候要先有
10/14 10:18, 7F

10/14 10:20, 7年前 , 8F
outer class的instance,所以是從outer class變數(或this)
10/14 10:20, 8F

10/14 10:21, 7年前 , 9F
後面加上new
10/14 10:21, 9F

10/14 10:21, 7年前 , 10F
而static inner class除了存取權(跟outer class互相都能存
10/14 10:21, 10F

10/14 10:23, 7年前 , 11F
取到private層級)外,就是個獨立class,instance間沒有關係
10/14 10:23, 11F

10/14 10:27, 7年前 , 12F
兩者共通的用途是class本身可以設成private/protected
10/14 10:27, 12F

10/14 10:27, 7年前 , 13F
控制要不要讓其他class用而已
10/14 10:27, 13F

10/14 11:22, 7年前 , 14F
感謝s大,所以說static inner class和獨立class差不多只
10/14 11:22, 14F

10/14 11:22, 7年前 , 15F
差在static還可以取用outer class的private content, 獨
10/14 11:22, 15F

10/14 11:22, 7年前 , 16F
立則不行,是嗎?
10/14 11:22, 16F

10/16 13:27, 7年前 , 17F
其實只有一個原則「任何用不到上層class的inner class
10/16 13:27, 17F

10/16 13:27, 7年前 , 18F
都該宣告為static」如此而已
10/16 13:27, 18F

10/16 13:28, 7年前 , 19F
除非你把它當作參數傳進來
10/16 13:28, 19F
文章代碼(AID): #1PuHnkt- (java)
文章代碼(AID): #1PuHnkt- (java)