🐵指尖猴全新升级
第8课:常量与命名
🔒

常量与命名

锁住不变的数据!

📖知识引入

🚫final常量
final修饰的变量只能赋值一次,像贴上"禁止改动"封条
📛全大写命名
常量名全大写用下划线分隔,如MAX_SIZE,醒目易识别
🐫小驼峰变量
变量名首字母小写后续单词首字母大写,如userName
🏛️大驼峰类名
类名每个单词首字母都大写,如HelloWorld
🎯见名知义
好名字胜过好注释,userName比u好,scoreSum比s好
💡
final常量声明时通常同时赋值,如final double PI = 3.14159;

🔍常量命名对照

public class Const {
    static final double PI = 3.14159;
    static final int MAX_STUDENT = 50;
    public static void main(String[] args) {
        int studentCount = 30;
        System.out.println("容量" + MAX_STUDENT);
        System.out.println("当前" + studentCount);
        System.out.println("π=" + PI);
    }
}
命名规范速查表:
┌────────────┬───────────────┬──────────────┐
│ 对象       │ 规范          │ 示例         │
├────────────┼───────────────┼──────────────┤
│ 常量       │ 全大写+下划线 │ MAX_SIZE     │
│ 变量/方法  │ 小驼峰        │ userName     │
│ 类         │ 大驼峰        │ HelloWorld   │
└────────────┴───────────────┴──────────────┘
final double PI = 3.14;  ← 常量
PI = 3.15;              ← 编译报错!

🎯小测验

第1题:用什么关键字声明常量?

第2题:常量名通常采用什么命名法?

第3题:变量userName是什么命名法?

📝本课知识点

  • ✓final声明常量
  • ✓常量全大写
  • ✓变量小驼峰
  • ✓类大驼峰
  • ✓见名知义
第8课完成!继续探索下一课吧 🚀