软件编程
位置:首页>> 软件编程>> java编程>> 带你了解Java中Static关键字的用法

带你了解Java中Static关键字的用法

作者:MMorant  发布时间:2021-11-07 15:04:32 

标签:Java,Static

Java中Static关键字的一些用法详解

1. Static 修饰类属性,因为静态成员变量可以通过类名+属性名调用,非静态成员变量不能通过类名+属性名调用;


public class Student {
   private static int number;//静态变量
   private String name;//非静态变量
   public static void main(String[] args) {
       System.out.println(Student.number);
       System.out.println(Student.name);//会报错 因为非静态成员变量不能通过类名+属性名调用
   }
}

2. Static 修饰类方法,可以通过类名.静态方法名的方式调用静态方法,不可以用类名.静态方法名调用非静态方法;


public class Student {
   public static void go(){};//静态方法
   public  void run(){};//非静态方法
   public static void main(String[] args) {
       Student.go();//可以用类名.静态方法名的方式调用静态方法
       Student.run();//报错,不可以用类名.静态方法名调用非静态方法
   }
}

3. 静态代码块,匿名代码块,构造函数。三者的调用顺序为(静态代码块(只调用1次) --> 匿名代码块 --> 构造函数)。


public class Student {
   //匿名代码块,每创建一个student对象就会调用一次匿名代码块
   {
       System.out.println("调用匿名代码块");
   }
   //静态代码块,和类加载一起发生,只会调用一次
   static {
       System.out.println("调用静态代码块");
   }
   //构造函数,每创建一个student对象就会调用一次该方法
   public Student() {
       System.out.println("调用构造函数");
   }
   public static void main(String[] args) {
       new Student();
       new Student();
   }
}

【第三点 测试结果】

带你了解Java中Static关键字的用法

来源:https://blog.csdn.net/qq_52979994/article/details/119743103

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com