首页 > 技术文章 > static 作用

lyh971134228 2016-11-17 19:24 原文

静态,定义静态变量或者静态函数的时候使用该关键字。 
被定义为static的函数,可以不需要new一个新类别而直接调用 
比如Math类里有一个,public static sub()方法,那么你可以直接Math.sub()调用该方法。 
所谓静态方法和静态变量,程序一启动,便在内存中初始化了。而不需要通过构造函数进行new。

 

Java中static关键字的作用: 
1、修饰类的变量,该变量称之为静态变量,所有此类的对象共享它: 

  1. class A {  
  2.     static int b;  
  3. }  



2、修饰类的方法,该方法称之为静态方法,所有此类的对象共享它: 

  1. class A {  
  2.     static void b(){  
  3.     }  
  4. }  



3、修饰嵌套类(接口),改类被称之为静态嵌套类(接口),通过静态的方式来访问它: 

  1. public class T {  
  2.     public static void main(String[] args) {  
  3.         A a = new A();  
  4.         A.B b = new A.B();  
  5.         A.C c = a.new C();  
  6.         System.out.println("a=" + a);  
  7.         System.out.println("b=" + b);  
  8.         System.out.println("c=" + c);  
  9.     }  
  10. }  
  11.   
  12. class A {  
  13.     static class B {  
  14.     }  
  15.   
  16.     class C {  
  17.     }  
  18. }  



4、声明一个类的静态区域,静态区域的代码执行完毕,方完成类的初始化: 

  1. class A {  
  2.     static {  
  3.         System.out.println("Hello World");  
  4.     }  
  5. }  



5、用法:static区域只能访问static变量/方法/嵌套类(接口)。 

推荐阅读