Static静态变量,静态方法,静态代码块

来源:互联网 发布:云科数据云一体机 编辑:程序博客网 时间:2024/05/21 18:47

首先这个知识点,我个人觉得比较重要:
1.静态变量:在一个JAVA类中,可以使用static关键字来修饰成员变量即静态变量,静态变量被所有实例所共享,比较特殊的一点可以使用”类名.变量名”的形式去访问。
eg

class Student{    static  String schoolName;}public class Example{    Student stu1 = new Student();    Student stu2 = new Student();    stu1.schoolName="111";    System.out.println(stu1.shcoolName);    System.out.println(stu2.shcoolName);//结果都是111}-------------------------------------------------------------------------------public class Examole7 {    public static void main(String[] args)    {        Student1 stu1 = new Student1();        Student1 stu2 = new Student1();        stu1.schoolName="111";        stu2.schoolName="222";        System.out.println(stu1.schoolName);        System.out.println(stu2.schoolName);//结果都是222    }}class Student1{    static String schoolName;}

上述的结果schoolName是静态变量,所在类的所有实例是共享的关系。注意一点:static只能修饰成员变量,不可以修饰局部变量,也就是static修饰的属性不可以放到一个具体的方法中。

有时候在不创造对象的前提下调用方法就可以使用静态方法,静态方法的定义很简单,就是在类中定义的方法前面加上static修饰词即可。同静态变量一样,静态方法可以使用“类名.方法名”的方式来访问。
eg:

public class Examole7 {    public static void main(String[] args)    {        Student1.student();    }}class Student1{    public static void student()    {        System.out.println("加油");    }}//输出加油

注意:在一个静态方法中只能访问用static修饰的成员,原因在于没有用static修饰的成员需要先创建对象才能访问,而静态方法在被调用时可以不创建任何对象。

3静态代码块:首先静态代码块和类是一起被加载的,由于类只可以加载一次,所以静态代码块也是能加载一次,通常使用静态代码块对类的成员变量进行初始化。
关于执行顺序可以看我前面写的静态方法,构造方法等的顺序

阅读全文
0 0