static关键字

1.修饰变量

一旦用了static关键字,那么这样的内容不再属于对象自己,而是属于类的,所以凡是本类的对象,都共享同一份,其实就是用的时候不用再加.了,例如下面类中的非static变量就要加this.

public class Student {
      private String name;
      private int age;
      // 学生的id
      private int sid;
      // 类变量,记录学生数量,分配学号
      public static int numberOfStudent = 0;
      public Student(String name, int age){
              this.name = name;
              this.age = age;
              // 通过 numberOfStudent 给学生分配学号
              this.sid = ++numberOfStudent;
} // 打印属性值
public void show() {
       System.out.println("Student : name=" + name + ", age=" + age + ", sid=" + sid );
}
}
public class StuDemo {
      public static void main(String[] args) {
              Student s1 = new Student("张三", 23);
              Student s2 = new Student("李四", 24);
              Student s3 = new Student("王五", 25);
              Student s4 = new Student("赵六", 26);
              s1.show(); // Student : name=张三, age=23, sid=1
              s2.show(); // Student : name=李四, age=24, sid=2
              s3.show(); // Student : name=王五, age=25, sid=3
              s4.show(); // Student : name=赵六, age=26, sid=4
}
}

2.修饰方法

一旦使用static修饰成员方法,那么这就成为了静态方法。静态方法不属于对象,而是属于类的,直接用类名称来调用,且对于本类中的静态方法可以省略类名称。如果没有static关键字,那么必须首先创建对象,然后通过对象才能使用它。

public class Myclass{
    public void method(){}
    public static void staticMethod(){} 
}
public class Demo01{
    Myclass my=new Myclass();
    my.method();//非static方法只能通过创建对象再调用
    my.staticMethod();//static方法也可以用对象调用,但是推荐下面那种写法,用类名调用
    Myclass.staticMethod();
}

3.总结:无论是成员变量还是成员方法,如果有了static关键字,都推荐使用类名称来调用

静态变量:类名称.静态变量
静态方法:类名称.静态方法

4.注意事项:

①静态只能直接访问静态,不能直接访问非静态。
原因:因为内存中先有的静态内容,后有的非静态内容,“先人不知道后人,后人却知道先人”。

public class Demo01{
    int num;
    static int numStatic;
    public void method(){
        System.out.println(num);
        System.out.println(numStatic);
    }
    public static void staticMethod(){
        System.out.println(num);//错误,静态不能访问非静态
        System.out.println(numStatic);
    } 
}

②静态方法当中不能用this

5.static的内存图

6.静态代码块

静态代码块:定义在成员位置,使用static修饰的代码块{}。
位置:类中方法外。
执行:随着类的加载而执行且执行一次,优先于main方法和构造方法的执行。

public class ClassName{
    static{
//执行语句
}
}

典型用途:用来一次性地对静态成员变量进行赋值

public class Game{
public static int number;
public static ArrayList<String> list;
static{
//给类变量赋值
    number=2;
    list=newArrayList<String>();
//添加元素到集合中
    list.add("张三");
    list.add("李四");
}
}