成员变量
Demo1:
- public
class Car { -
private String color; // 定义汽车颜色,全局变量 -
private int numLuntai; // 定义汽车轮胎数,全局变量 -
-
public Car(String color, int numLuntai){ -
super(); -
this.color = color; -
this.numLuntai = numLuntai; -
} -
public void run() { -
System.out.println(this.numLuntai+ "个轮子的" +this.color + "轿车在马路上行驶着"); -
} - }
- public
class ClassTest { -
public static void main(String[] args){ -
Car bmw = new Car("黑色", 4); // 创建一个轿车对象,名字为bmw -
bmw.run(); -
} - }
运行结果:
4个轮子的黑色轿车在马路上行驶着
- for(int
i = 0; i < args.length; i++) { -
...... - }
又例如写在成员方法中变量是局部变量。
- publicclass
Car { -
private String color; // 定义汽车颜色,全局变量 -
private int numLuntai; // 定义汽车轮胎数,全局变量 -
public Car(String color, int numLuntai){ -
super(); -
this.color = color; -
this.numLuntai = numLuntai; -
} - public
void run() { -
String carName=”宝马牌”; //这个就是局部变量 -
System.out.println(this.numLuntai+ "个轮子的" +this.color + carName+"轿车在马路上行驶着"); -
} - }
- publicclass
ClassTest { -
public static void main(String[] args){ -
Car bmw = new Car("黑色", 4); // 创建一个轿车对象,名字为bmw -
bmw.run(); -
} - }
结果:
4个轮子的黑色宝马牌轿车在马路上行驶着
成员变量和局部变量的区别
静态变量
示例:
- class
Person{ -
//成员变量,实例变量 -
String name; -
//静态变量,类变量 -
//所有对象共享的属性用static修饰 -
static String country = "CN"; -
public void show(){ -
System. out.println(country + ":" + name); -
//等效语句:System.out.println(Person.country+ ":" + this.name); -
} - }
- class
StaticDemo{ -
public static void main(String[]args){ -
Person p = new Person(); -
System. out.println(p.country); -
//可以用类名直接调用 -
System. out.println(Person.country); -
} - }
结果:
CN
CN
成员变量和静态变量的区别
列表对比:
| 成员变量 | 局部变量 | 静态变量 |
定义位置 | | 方法中,或者方法的形式参数 | 在类中,方法外 |
初始化值 | 有默认初始化值 | 无,先定义,赋值后才能使用 | 有默认初始化值 |
调用方式 | 对象调用 | --- | 对象调用,类名调用 |
存储位置 | 堆中 | 栈中 | 方法区 |
生命周期 | 与对象共存亡 | 与方法共存亡 | 与类共存亡 |
别名 | 实例变量 | --- | 类变量 |
小结: