When should you use a static method?
- when your method is related to the object's characteristics
- when you want your method to be available independently of class instances
- when your method uses an object's instance variable
- when your method is dependent on the specific instance that calls it
answer:B
static 意思是在記憶體中切出一塊專門存放數據,
而這一塊資料並不會隨著 new 物件而被產生或銷毀
換言之:
Static method 屬於class,,而不是屬於Object。
下面程式碼作為範例:
class Toyota {
static int totalCarsNum = 0 ;
int carNum = 0 ;
public void add(){
totalCarsNum++;
carNum++;
}
}
class test{
public static void main(String[] args) {
Toyota car1 = new Toyota();
Toyota car2 = new Toyota();
car1.add();
car2.add();
System.out.println("car1Num="+car1.carNum);
System.out.println("car2Num="+car2.carNum);
System.out.println("totalCarsNum="+car1.totalCarsNum);
}
}
console :
car1Num=1
car2Num=1
totalCarsNum=2
原因:
carNum 前面沒有加入 static ,表示此參數隸屬於Object
所以 car1 != car2 ,故兩個carNum的記憶體位置不共用
totalCarsNum 則隸屬於此class
所以全部的Toyota的 totalCarsNum 都使用同一個記憶體位址