标签:
package unit4; public class staticvartest { int a; static int b; public staticvartest() { // TODO Auto-generated constructor stub a=20;b=30; } public static void main(String[] args) { staticvartest ss =new staticvartest(); staticvartest sb = new staticvartest(); ss.a=60; ss.b=100; sb.a=80; sb.b=1000; System.out.println(ss.a+" "+ss.b); System.out.println(sb.a+" "+sb.b); System.out.println(b); } }
输出结果:
60 1000 80 1000 1000
被static修饰的成员和函数,在内存中只有一个,通常用来当作全局变量。整个类都可以访问。
类成员方法:可以通过类名直接访问,不用创建实例对象,比如说Math类下的函数,都是这个道理。
package unit4; public class Staticmethod { public static int add(int x,int y){ return x+y; } public static void main(String[] args){ int result = Staticmethod.add(20,30); System.out.print(result); } }
static代码块:
package unit4; public class staticvartest { int a; static int b; public staticvartest() { // TODO Auto-generated constructor stub a=20;b=30; } public static void main(String[] args) { staticvartest ss =new staticvartest(); staticvartest sb = new staticvartest(); ss.a=60; ss.b=100; sb.a=80; sb.b=1000; System.out.println(ss.a+" "+ss.b); System.out.println(sb.a+" "+sb.b); System.out.println(b); } }
标签:
原文地址:http://www.cnblogs.com/superxuezhazha/p/5693485.html