java关键字“static”
Java中static使用方法
1.static静态变量
1)静态变量:
内存中只占用一块区域,对类内的对象共享;
使用:
1.类名.静态变量
2.对象.静态变量
1 package test2;
2 import java.lang.String; 3 public class test2 { 4 public static int count =0;
//相当于类内自带的变量可以直接使用无需引用
//数值只要改动就会在类内改变;
5 public test2() { 6 count++;
7 System.out.println("test : "+count); 8
9 10 } 11 private static int size; 12 public static void main(String[] args) { 13 test2 a = new test2(); 14 test2 b = new test2(); 15 String[] s = {"a","b","c"}; 16 setSize(5); 17 getSize(); 18 System.out.println("Size of duck is "+size+";"); 19 } 20 public static void setSize(int s) { 21 size = s; 22 } 23 public static int getSize() { 24 return size; 25 } 26 }
2)静态方法
静态方法与静态变量有很多地方类似,但是要注意静态方法只能调用静态变量,而普通方法可以直接调用静态变量;
静态方法调用:
类名.静态方法(一般都采用此方法)
对象.静态方法
代码展示如下:
1 package test1; 2 3 /** 4 * Created by Administrator on 2020/6/4. 5 */ 6 public class Static { 7 private static int count=0; 8 public static void test(){ 9 count++; 10 System.out.println(count); 11 } 12 public static void test1(){ 13 count++; 14 System.out.println(count); 15 } 16 public static void main(String[] args) { 17 Static.test(); 18 Static.test1(); 19 } 20 }
输出结果:
1
2
3)静态代码块
静态代码块加载速度提前于主函数;
一个类内可以有多个静态代码块,他们按照顺序有序加载;
package test1;
/**
* Created by Administrator on 2020/6/4.
*/
public class Static {
public Static(){
System.out.println("构造函数");
}
private static int count=0;
static{
count++;
System.out.println(count);
}
static{
count++;
System.out.println(count);
}
public static void main(String[] args) {
Static one = new Static();
System.out.println("main");
}
}
4)另外静态代码块与内部类也有很大的用处,有兴趣的可以自己研究一下。(哈哈,暴露了,我还不会)
随笔中的内容是我的学习笔记,非常愿意与大家共享,希望我们一起进步。

浙公网安备 33010602011771号