Java 定義識別字可用任何 Unicode 符號,因此中文字、日文平假名片假名等都可用為識別字名稱,長度不限,但是習慣上仍是以英文二十六的大小寫字母為主,另加上數字、底線符號及 dollar sign ,如下
_ | $ | |||||||||||
a | b | c | d | e | f | g | h | i | j | k | l | m |
n | o | p | q | r | s | t | u | v | w | x | y | z |
A | B | C | D | E | F | G | H | I | J | K | L | M |
N | O | P | Q | R | S | T | U | V | W | X | Y | Z |
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
通常識別字會由具有意義的英文單字組成,因此會由字母開始,而非數字 (0-9) 、底線符號 (_) 或 dollar sign ($) ,至於單字數量依需要而定。如果單一識別字利用超過一個英文單字組成,各單字之間不可有空格,因為空格會讓編譯器認為是前後分別是兩個不同的識別字。識別字也不可與關鍵字的名稱相同。
注意,任何識別字都不能用數字 (0-9) 開頭,也就是不能拿數字作為識別字的第一個字元,因為數字會先被當成 literal 處理。識別字的第二個字元後就沒有限制,可以用數字或是任何 Unicode 符號。
注意,英文字母中大寫與小寫是不同的,例如 A 與 a 會被當成兩個不同的識別名稱。
連接多英文單字組合的識別字,可用底線符號 (_) ,或是大寫駝峰型 (upper camel case) 或是小寫駝峰型 (lower camel case) 。大寫駝峰型如
SimpleGame MyStory ThreadTestDrive RunThreads TextArea ButtonOne MidiEvent ShortMessage MyObject BExample |
小寫駝峰型如
actionPerformed setUpNetworking doSomething getField getTitle makeEvent turnOvenOn takeRisk printList myCanvas |
若是只使用一個英文單字,下面是全部用小寫字母的例子
clone equals i obj1 move paint run play sleep name color |
首字母大寫的例子
Zoo Animal Bird Day Outter Producer Server Data Filename Example |
或全部的字母都大寫,如用在常數 (constant)
START END RIGHT BEGIN |
自行命名的識別字名稱應統一格式,一般來說,類別名稱通常會用多單字組合成的大寫駝峰型,成員用某一英文單字的小寫或多單字組合成的小寫駝峰型。
另外,方法的第一個英文單字通常會用動詞,屬性則用名詞。方法內常需要使用區域變數 (local variable) ,比較常用小寫英文單字,或是小寫駝峰型。
識別字名稱所採取的英文單字最好跟用途有關,因為這樣才容易辨識該識別字的用途,後續維護或與團隊間溝通也才比較方便。
中英文術語對照 | |
---|---|
識別字 | identifier |
第三方 library | third-party library |
dollar sign | dollar sign |
literal | literal |
大寫駝峰型 | upper camel case |
小寫駝峰型 | lower camel case |
常數 | constant |
區域變數 | local variable |
參考資料
http://download.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
http://download.oracle.com/javase/tutorial/java/javaOO/variables.html
http://java.sun.com/docs/books/jls/third_edition/html/lexical.html
http://download.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
http://download.oracle.com/javase/tutorial/java/javaOO/variables.html
http://java.sun.com/docs/books/jls/third_edition/html/lexical.html
沒有留言:
張貼留言