Static变量和方法

一、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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值