삼성SDS_멀티캠퍼스/Java

9일 차 정적변수

박성우기 2015. 9. 17. 09:31
반응형

class Car {


private int speed;

private int mileage;

private String color;

private int id;

public static int numOfCars = 0;


public int getSpeed() {

return speed;

}


public void setSpeed(int speed) {

this.speed = speed;

}


public int getMileage() {

return mileage;

}


public void setMileage(int mileage) {

this.mileage = mileage;

}


public String getColor() {

return color;

}


public void setColor(String color) {

this.color = color;

}


public int getId() {

return id;

}


public void setId(int id) {

this.id = id;

}


@Override

public String toString() {

return "Car [speed=" + speed + ", mileage=" + mileage + ", color=" + color + ", id=" + id + "]";

}


public Car() {


id = ++numOfCars;


}


}



public class Test {


public static void main(String[] args) {


System.out.println(Car.numOfCars);

Car abbacha = new Car();

System.out.println(Car.numOfCars);


Car abbacha2 = new Car();

System.out.println(Car.numOfCars);

System.out.println(abbacha);

System.out.println(abbacha2);

}


}










이처럼 static(정적)변수는 생성자를 호출해도 매번 새롭게 만드는 것이 아니라


프로그램이 끝날때까지 계속 고정된 메모리 값을 가지고 있다


그래서 0,1,2 이렇게 뜨는 것



static변수가 아니라면 무조건 1로 뜰 것이다



반응형