三类变量的使用方法
- 类变量
类范围内直接调用,static关键字修饰,可以不初始化
- 实例变量
通过实例对象调用,可以不初始化
- 局部变量
仅在方法内部调用,且必须先声明和初始化值
public class Variable {
static int num = 10; // 类变量
String name = "CrazyGod"; // 实例变量
public void method() {
int i = 0; // 局部变量
}
}
常量
public class Constant {
static final double PI = 3.14;
public static void main(String[] args) {
System.out.println(PI);
}
}
命名规则
- 见名知意
- 类名:首字母大写,大驼峰命名
- 方法名、变量名:首字母小写,小驼峰命名
- 常量:大写字母和下划线:CONSTANT_VALUE
- 包名:小写
代码测试
public class Demo02 {
/*
类变量和实例变量:
如果不自行初始化,这个类型的默认值
整数:0,浮点数:0.0,布尔值:false
除了基本数据类型,其余的默认值都是null
*/
// 类变量 static
static double salary = 20_0000;
static int year;
static final double PI = 3.14;
// 实例变量:从属于对象
String name;
int age;
// main方法
public static void main(String[] args) {
// 局部变量:必须声明和初始化值
int i = 10;
System.out.println(i);
// 实例变量
Demo02 demo02 = new Demo02();
System.out.println(demo02.age);
System.out.println(demo02.name);
// 类变量
System.out.println(salary);
System.out.println(year);
System.out.println(PI);
}
}