-
9일 차 정적변수삼성SDS_멀티캠퍼스/Java 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로 뜰 것이다
반응형'삼성SDS_멀티캠퍼스 > Java' 카테고리의 다른 글
9일 차 사용관계 (0) 2015.09.17 9일 차 생성자의 정적변수 접근 (0) 2015.09.17 8일 차 시험(깊은 복사, 얕은 복사) (0) 2015.09.16 8일 차 중간점검(생성자) (0) 2015.09.16 8일 차 생성자 하나 만들어보기 (0) 2015.09.16