一、static变量和对象的数据成员变量在static函数和对象的成员函数中的调用权限,及在main函数中的调用权限和方法
public class StaticTest {
private int value;
private static int count;
public void print() {
System.out.println(“value=”+value);
System.out.println(“count=”+count);
}
public static void print1() {
// System.out.println(“value=”+value);
System.out.println(“count=”+count);
}
public static void main(String[] args) {
// print();
print1();
}
}
value是对象的,count是类的
public void print()是对象的方法,需创建对象才能使用;public static void print1()是类的方法,不需要创建对象就能使用
value不能用在static方法中
在main函数中,print()未定义对象不能使用,print1()是类方法可以直接使用
public class StaticTest0 {
public static void main(String[] args) {
StaticTest.print1();
}
}
当在另一个java源文件中调用print1()的方法为StaticTest.print1();
不能在一个java源文件中调用print()
二、static变量和对象的数据成员变量定义和显示的方式不同输出结果不同
public class StaticTest {
private int value;
private static int count;
public StaticTest(int value) {
this.value=value;
count=value+1;
}
}
1)全部定义完对象再显示
public static void main(String[] args) {
StaticTest st=new StaticTest(10);
StaticTest st1=new StaticTest(100);
System.out.println(“st_value=”+st.value);
System.out.println(“st_count=”+count);
System.out.println(“st1_value=”+st1.value);
System.out.println(“st1_count=”+count);
}
输出结果:
st_value=10
st_count=101
st1_value=100
st1_count=101
2)一边定义一边显示
public static void main(String[] args) {
StaticTest st=new StaticTest(10);
System.out.println(“st_value=”+st.value);
System.out.println(“st_count=”+count);
StaticTest st1=new StaticTest(100);
System.out.println(“st1_value=”+st1.value);
System.out.println(“st1_count=”+count);
}
输出结果:
st_value=10
st_count=11
st1_value=100
st1_count=101
三、for循环定义100次static变量value逐次增加
public class StaticTest {
private int value;
private static int count;
public StaticTest(int value) {
this.value=value;
count++;
}
public static void main(String[] args) {
for(int i=1;i<=100;i++)
new StaticTest(10);
System.out.println(“count=”+count);
}
}
输出结果:
count=100