static關鍵字
- 作用:是一個修飾符,用於修飾成員(成員變量,成員方法)
- 1、被static修飾後的成員變量只有一份
- 2、當成員被static修飾後,多了一種訪問方式,處理可以對象調用之外,還可以被類直接調用(類名. 靜態成員)
static的特點:
- 隨着類的加載而被加載
- 優先於對象的存在
- 被所有對象所共享的
- 可以直接被類名所調用
存放位置
- 類變量隨着類的加載而存在於data內存區
- 實例變量隨着對象的建立而存在於堆內存
public class test_static {
public static void main(String[] args){
Student6 A = new Student6();
A.country = "中國";
Student6 B = new Student6();
System.out.println(B.country);
System.out.println(Student6.country); //可以類名直接調用靜態變量
}
}
class Student6{
String name;
int age; //實例變量
static String country; //靜態變量(類變量)
}
靜態方法
- 靜態方法只能訪問靜態成員
- 非靜態的方法既能訪問靜態的成員(成員變量,成員方法),也能訪問非靜態成員
- 靜態的方法中不可以定義this super 關鍵字,因爲靜態優先於對象存在,所以靜態方法不可以出現this
public class test_static1 {
public static void main(String[] args){
whale3 A = new whale3();
A.descrip();
A.descrip1();
}
}
class whale3{
String name;
static int age;
static void descrip(){
System.out.println(age);
}
static void descrip1(){
String address = "冰島"; //局部變量不能用static修飾
System.out.println(address);
}
}
什麼時候使用靜態成員
- 當屬同一個類的所有對象出現共享數據時,可以用static修飾這個成員變量
什麼時候使用靜態方法
- 當功能內部沒有訪問到非靜態的成員時(對象特有的數據),那麼該功能可以定義成靜態的