在Java中,將關鍵字static分爲三部分進行討論,分別爲Java靜態變量、Java靜態方法、Java靜態類java
Java Static Variables
- Java instance variables are given separate memory for storage. If there is a need for a variable to be common to all the objects of a single java class, then the static modifier should be used in the variable declaration.
- Any java object that belongs to that class can modify its static variables.
- Also, an instance is not a must to modify the static variable and it can be accessed using the java class directly.
- Static variables can be accessed by java instance methods also.
- When the value of a constant is known at compile time it is declared ‘final’ using the ‘static’ keyword.
(1)類的非靜態變量會被每個被實例化的對象分配一個內存空間,而靜態變量會被類全部實例化的對象共享同一塊內存空間。this
(2)類的任何一個實例化對象對該靜態變量的操做都會改變該靜態變量的值spa
(3)能夠直接經過 ClassName.static-Variable 對靜態變量進行訪問對象
(4)static 和final用來修飾成員變量和成員方法,可簡單理解爲「全局常量」。內存
Java Static Methods
- Similar to static variables, java static methods are also common to classes and not tied to a java instance.
- Good practice in java is that, static methods should be invoked with using the class name though it can be invoked using an object. ClassName.methodName(arguments) or objectName.methodName(arguments)
- General use for java static methods is to access static fields.
- Static methods can be accessed by java instance methods.
- Java static methods cannot access instance variables or instance methods directly.
- Java static methods cannot use the ‘this’ keyword.
(1)靜態方法能夠直接經過類名調用,任何的實例也均可以調用。it
(2)靜態方法中不能用this和super關鍵字,不能直接訪問所屬類的實例變量和實例方法(就是不帶static的成員變量和成員成員方法),只能訪問所屬類的靜態成員變量和成員方法 (這點和C++中是一致的)io
(3)由於static方法獨立於任何實例,所以static方法必須被實現,而不能是抽象的abstract。class
Java Static Classes
- For java classes, only an inner class can be declared using the static modifier.
- For java a static inner class it does not mean that, all their members are static. These are called nested static classes in java
(1)只有內部類才能被聲明爲靜態類變量