一、命名规则总结
元素 | 命名规则 | 示例 |
---|---|---|
变量名 | 小驼峰命名法 | studentAge |
方法名 | 小驼峰命名法 | calculateTotal() |
类名 | 大驼峰命名法 | StudentInfo |
接口名 | 大驼峰命名法 | PaymentProcessor |
常量名 | 全大写+下划线 | MAX_RETRY_COUNT |
包名 | 全小写+. 分隔 | com.example.myapp |
注:包名的命名一般以“公司域名的反写+包的作用”,一般省略“.www”。
二、驼峰命名法详解
1. 小驼峰命名法(Camel Case)
- 规则:第一个单词以小写字母开头,后续每个单词的首字母大写,其他字母小写。
- 用途:通常用于变量名、方法名。
- 示例:
- 变量名:
int studentAge; String firstName; double accountBalance;
- 方法名:
public void calculateTotal() { ... } public String getUserName() { ... }
- 变量名:
2. 大驼峰命名法(Pascal Case)
- 规则:每个单词的首字母都大写,包括第一个单词,其他字母小写。
- 用途:通常用于类名、接口名。
- 示例:
- 类名:
public class StudentInfo { ... } public class AccountManager { ... }
- 接口名:
public interface PaymentProcessor { ... }
- 类名:
三、变量命名规则
-
不能以数字开头
变量名必须以字母(A-Z 或 a-z)或下划线
_
或美元符号$
开头。- 正确示例:
int age; int _temp; int $price;
- 错误示例:
int 1stNumber; // 错误:不能以数字开头
- 正确示例:
-
后续字符可以是字母、数字、下划线或美元符号
变量名的第二个及后续字符可以包含字母(A-Z 或 a-z)、数字(0-9)、下划线
_
或美元符号$
。- 正确示例:
int student1; int total_value; int $discount; int _tempValue2;
- 正确示例:
-
不能使用Java的关键字或保留字
Java关键字(如
int
、class
、if
、else
等)不能作为变量名。- 错误示例:
int class; // 错误:class是关键字 int public; // 错误:public是关键字
- 错误示例:
-
区分大小写
Java中的变量名是区分大小写的,例如
student
和Student
是两个不同的变量。- 示例:
int student = 10; int Student = 20; System.out.println(student); // 输出10 System.out.println(Student); // 输出20
- 示例:
-
长度不限,但尽量保持简洁
变量名可以很长,但推荐保持清晰简洁,避免冗长的变量名。
四、变量命名规则总结
- 不能以数字开头。
- 只能包含字母、数字、下划线
_
或美元符号$
。 - 避免使用Java关键字和保留字。
- 采用小驼峰命名法,变量名有意义。
- 注意区分大小写。