Java 中的類和靜態變數
類變數也稱為靜態變數,並且在方法外使用關鍵字“static”進行宣告。
靜態變數在類的所有例項之間是通用的。一個變數的單個副本在所有物件之間共享。
示例
public class Demo{
static int my_count=2;
public void increment(){
my_count++;
}
public static void main(String args[]){
Demo obj_1=new Demo();
Demo obj_2=new Demo();
obj_1.increment();
obj_2.increment();
System.out.println("The count of first object is "+obj_1.my_count);
System.out.println("The count of second object is "+obj_2.my_count);
}
}輸出
The count of first object is 4 The count of second object is 4
一個名為 Demo 的類定義了一個靜態變數,以及一個名為“increment”的函式,該函式遞增靜態變數的值。主函式建立該類的兩個例項,並且在兩個物件上呼叫 increment 函式。計數顯示在螢幕上。它表明靜態變數在物件之間共享。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP