Java static理解

记录使用过程中混淆或者不清楚的点。

static

参考:公众号《方志明》 感谢作者。

  关键字static声明的方法、变量,可直接通过类名进行访问。不需要new对象去访问。

  1. 没有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();
     }
    
  2. 静态变量在类初此加载时被初始化。且被所有对象共享,内存中只有一个副本。
    在主程序中创建两个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则是对象私有。

    在这里插入图片描述

  3. 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只执行了一次。构造函数执行了两次。

    在这里插入图片描述

  4. static不允许用来定义局部变量。

  5. 类的构造器也是静态方法。
    所以在类的构造器可以使用this关键字引用静态方法。

     public CustomerService(String name,int age) {
         this.age = age;
         this.name = name;
     }
    

    但是编辑器给出警告,尽量不要再类内部使用静态方法、变量。在类实例化使用。
    在这里插入图片描述


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

heroboyluck

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值