一、静态变量
(一)静态变量
用static修饰,也叫类变量,所有实例共享一块内存空间。通常使用类名访问。
(二)实例变量
未用static修饰。每个实例具有自己的内存空间。必须使用实例名访问。
二、举例
(一)静态变量
1.代码
package csdn.every.day;
public class Counter {
public int x = 0; //为实例变量
public static int y = 0; //为静态变量
public Counter(){ //定义构造方法
x = 100;
}
public static void main(String[] args) {
Counter c1 = new Counter(); //声明变量,创建对象
Counter c2 = new Counter();
c1.y = 100;
c2.y = 200;
System.out.println(c1.y); //c1.y为200,因为c1.y和c2.y为静态变量共享一个空间
}
}
2.结果
(二)静态常量
1.注意
通常,static与final一起使用来定义类常量。
例如,Math类中定义的两个类常量:
public static final double E = 2.718281828459045;
public static final double PI = 3.141592653589793;
2.举例——静态常量
package csdn.every.day;
public class Counter2 {
public static void main(String[] args) {
System.out.println("圆的面积="+Math.PI*10*10);
}
}
3.结果
二、静态方法
(一)静态方法
静态方法
用static修饰,也叫类方法。只能访问静态变量。通常使用类名访问。
实例方法
未用static修饰,可访问实例变量和静态变量。必须使用实例名调用。
(二)举例——静态方法
1.代码
package csdn.every.day;
public class SomeClass {
int x = 5;
static int y = 48;
public static void display1(){ //静态方法
y = y + 10;
System.out.println("y="+y);
}
public void display2(){ //实例方法
x = x + 5;
System.out.println("x="+x);
y = y + 10;
System.out.println("y="+y);
}
public static void main(String[] args) {
SomeClass sc = new SomeClass();
SomeClass.display1();
sc.display2();
}
}
2.结果