static关键字的做用?

Java Language Specification, 3rd 写道

8.4.3.2 static Methodsapp

A method that is declared static is called a class method. A class method is always invoked without reference to a particular object. An attempt to reference the current object using the keyword this or the keyword super or to reference the type parameters of any surrounding declaration in the body of a class method results in a compile-time error. It is a compile-time error for a static method to be declared abstract.this

A method that is not declared static is called an instance method, and sometimes called a non-static method. An instance method is always invoked with respect to an object, which becomes the current object to which the keywords this and super refer during execution of the method body.对象

15.8.3 thisci

The keyword this may be used only in the body of an instance method, instance initializer or constructor, or in the initializer of an instance variable of a class. If it appears anywhere else, a compile-time error occurs.作用域

static修饰的变量和方法是独立于对象而存在的,不产生副本,能够直接用类名来调用。

一.static修饰的变量

static修饰的变量当且仅当类被加载时初始化。而非static变量在实例化对象时被初始化,产生多个副本,多个对象不互相影响。it

局部变量不能被static修饰io

static不改变变量和方法的做用域,其做用域只受四个访问修饰符的影响class

二.static修饰的方法

被static修饰的方法内部不能调用非static的变量和方法,非static方法内部能够调用static变量的方法和变量。import

三.static修饰的代码块

static修饰的代码块在且只在类被加载时执行一次。变量

执行顺序:static代码块优于构造块,优于构造方法。

总结

  1. static class, 声明静态内部类;
  2. static field, 声明静态成员变量;
  3. static method, 声明静态成员方法;
  4. static {...}, 声明静态代码块;
  5. import static package, 声明静态成员变量可见.
相关文章
相关标签/搜索