zoukankan      html  css  js  c++  java
  • Java的static关键字

    1.可以修饰的对象有:变量,方法,代码块,(引入包名)

       对应的就是:静态变量/类变量;静态方法;静态代码

         eg: public class Student{

                    public static int a = 0;

                    public static int getValue(){

                           return a;

                    }

               }

           静态引入包名: 

    1 import static java.util.Math;//在包名前多了一个static关键字
    2 public class Test{
    3       public static void main(String[] args){
    4            //这个sin是Math类中的静态方法,
    5           //以前常用Math.sin()来调用,静态引入后则无需类名
    6             double a = sin(45);
    7       }
    8 }
    View Code

    2.凡是被static修饰的,都是类级别的,所有对象一起共享的

            看例子:

     1 public class User {
     2     private static int userNumber  = 0 ;
     3     
     4     public User(){
     5         userNumber ++;//每创建一个对象就加1
     6     }
     7     
     8     public static void main(String[] args) {
     9         User user1 = new User();//此时 userNumber为1
    10         User user2 = new User();//此时 userNumber为2
    11         
    12         System.out.println("user1 userNumber:" + User.userNumber);
    13         System.out.println("user2 userNumber:" + User.userNumber);
    14     }
    15 }    
    16 ------------
    17 Output:
    18 user1 userNumber:2
    19 user2 userNumber:2
    View Code

    3.可以直接用类名来访问,而不必实例一个对象才能使用。

             eg: Student.getValue();//直接类名调用

                   或者 Student s = new Student();

                          s.getValue();//也可以通过先生成实例再调用,但推荐第一种

    4. 使用static要注意的

            4.1. static变量在定义时必须要进行初始化,且初始化时间要早于非静态变量。

            4.2. static修饰的方法,只能调用static变量或方法,而不能调用非static的变量或方法。

            4.3.不能以任何形式引用this、super。(因为它们也不是static的)

          

          总结:无论是变量,方法,还是代码块,只要用static修饰,就是在类被加载时就已经"准备好了",也就是可以被使用或者已经被执行,都可以脱离对象而执行。

                  反之,如果没有static,则必须要依赖于对象实例,记住两点,凡是static只有两层含义,静态/共享

    参考这里非常详细

  • 相关阅读:
    [daily][dpdk] 内核模块(网卡驱动)无法卸载
    [development][tcp/ip][ids] 一个简单有参考价值的库 libnids
    [development][http][libhtp] suricata的http库--libhtp
    [skill][http] http管道化连接
    [skill][telnet] 用telnet获取一个网页
    [daily][grub2] grub2修改内核选项
    [knowledge] big data things
    [knowledge][dpdk] open data plane
    [daily] docker
    [knowledge] 停止等待协议
  • 原文地址:https://www.cnblogs.com/tommy-huang/p/4277971.html
Copyright © 2011-2022 走看看