好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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

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

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

?

1

2

3

4

5

6

7

8

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 修饰类方法,可以通过类名.静态方法名的方式调用静态方法,不可以用类名.静态方法名调用非静态方法;

?

1

2

3

4

5

6

7

8

public class Student {

     public static void go(){}; //静态方法

     public   void run(){}; //非静态方法

     public static void main(String[] args) {

         Student.go(); //可以用类名.静态方法名的方式调用静态方法

         Student.run(); //报错,不可以用类名.静态方法名调用非静态方法

     }

}

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

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();

     }

}

【第三点 测试结果】

总结

本篇文章就到这里了,希望能给你带来帮助,也希望您能够多多关注的更多内容!

原文链接:https://blog.csdn.net/qq_52979994/article/details/119743103

查看更多关于带你了解Java中Static关键字的用法的详细内容...

  阅读:17次