首页 > 技术文章 > static

324sige 2016-07-29 09:49 原文

 一、静态代码块

  1、类被装载时,所有的static语句被运行。

  2、然后调用main(),main() 调用meth() 

  注意:在一个static 方法中引用任何实例变量都是非法的。

 

 

	有时你希望定义一个类成员,使它的使用完全独立于该类的任何对象。可以使用static

作用一、直接引用,无需声明对象

public class Test {
	
	public static void print(String str) {
		System.out.println(str);
	}	
}

public class hello {
	
	public static void main(String args[]){	
		/**
		 * 无需Test test=new Test();
		 * Test.print("hello !");
		 */

		Test.print("hello !");		
	}
}



作用二、全局变量,所有对象共有

public class Test {
	
	private int num1=0;
	private static int num2=0;
	
	public int getNum1() {
		return num1;
	}
	public void setNum1(int num1) {
		this.num1 = num1;
	}
	public static int getNum2() {
		return num2;
	}
	public static void setNum2(int num2) {
		Test.num2 = num2;
	}	
}


public class hello {
	
	public static void main(String args[]){	
		Test test1=new Test();
		Test test2=new Test();
		
		test1.setNum1(1);
		test1.setNum2(1);
		
		System.out.println(test2.getNum1());
		System.out.println(test2.getNum2());		
	}
}

结果:0, 1

  

推荐阅读