记录使用过程中混淆或者不清楚的点。
static
参考:公众号《方志明》 感谢作者。
关键字static
声明的方法、变量,可直接通过类名进行访问。不需要new
对象去访问。
-
没有
new
对象,就没有this
上下文环境,就不能使用this
调用非静态方法、使用非静态变量。public class CustomerService { public static String name="Spring boot"; public String age="25"; public void printAge(){ System.out.println(name); System.out.println(age); printName(); } public static void printName(){ System.out.println(name); // System.out.println(this.age); } }
使用非静态变量提示错误。
或者使用this
提示错误。
在静态方法中new
一个对象就调用非静态方法、变量了。public static void printName(){ CustomerService customerService = new CustomerService(); System.out.println(name); System.out.println(customerService.age); // customerService.printAge(); }
-
静态变量在类初此加载时被初始化。且被所有对象共享,内存中只有一个副本。
在主程序中创建两个CustomerService
对象实例、观察静态变量和静态变量。这边是通过类的构造器对变量进行初始化赋值,具体查看第五点
public static void main(String[] args) { CustomerService c1 = new CustomerService("高飞",42); System.out.println(c1.name+","+c1.age); CustomerService c2 = new CustomerService("红颜",32); System.out.println(c1.name+","+c1.age); System.out.println(c2.name+","+c2.age); // new CustomerService(); System.out.println("main:"+CustomerService.name); SpringApplication.run(DemoApplication.class, args); }
日志打印
name
静态变量的值为最后一次的对象实例,说明了静态变量被对象共享。而普通变量age
则是对象私有。 -
static
代码块,在类初次加载时执行,且执行一次。(可用作初始化操作)在类内部但不能在方法中。多个
static
代码块,按序执行。static{ System.out.println("static block"); } public CustomerService() { System.out.println("construct"); } //在主程序中调用 public static void main(String[] args) { new CustomerService(); new CustomerService(); SpringApplication.run(DemoApplication.class, args); }
日志打印中
static
只执行了一次。构造函数执行了两次。 -
static
不允许用来定义局部变量。 -
类的构造器也是静态方法。
所以在类的构造器可以使用this
关键字引用静态方法。public CustomerService(String name,int age) { this.age = age; this.name = name; }
但是编辑器给出警告,尽量不要再类内部使用静态方法、变量。在类实例化使用。