개인공부/java
Static 문제 풀이
케잉
2024. 8. 20. 17:02
public class CarMain {
public static void main(String[] args) {
Car car1 = new Car("K3");
Car car2 = new Car("G80");
Car car3 = new Car("Model Y");
Car.showTotalCars(); //구매한 차량 수를 출력하는 static 메서드
}
}
totalCars++;를 static 메서드인 showTotalCars에 적는다면 왜 구매한 차량수가 누적되어 출력되지 않는 것인가??
왜 Car 생성자 안에 totalCars++;를 적어야만 누적되어 출력되는 것인가?
public class Car {
private String name;
private static int totalCars;
Car(String name){
this.name = name;
System.out.println("차량구입, 이름: "+ name);
totalCars++;
}
public static void showTotalCars(){
System.out.println("구매한 차량 수: " + totalCars); //static 메서드라 static 변수 사용
}
}
1. showTotalCars() 메서드에 totalCars++가 있을 때
public static void showTotalCars() {
totalCars++;
System.out.println("구매한 차량 수: " + totalCars);
}
showTotalCars() 메서드를 호출할 때마다 totalCars의 값이 1씩 증가한다
하지만 showTotalCars() 메서드는 Car 객체를 생성할 때 자동으로 호출되지 않기 때문에, Car 객체를 생성할 때마다 totalCars가 증가하지 않는다
객체를 3번 생성한 후에 showTotalCars()를 한 번만 호출하면, 그때서야 totalCars가 1 증가하고, 구매한 차량 수가 1로 출력되고 다시 showTotalCars()를 호출할 때마다 또 1씩 증가한다.
2. Car 생성자 안에 totalCars++를 넣었을 때
Car(String name) {
this.name = name;
System.out.println("차량구입, 이름: " + name);
totalCars++; // 여기에서 totalCars가 증가함
}
생성자 안에 totalCars++가 있으면, Car 객체가 생성될 때마다 totalCars의 값이 자동으로 1씩 증가한다
totalCars는 구매한 차량의 총 수를 나타내는 변수다.
이 값을 객체가 생성될 때마다 증가시키려면, 생성자 안에서 증가시켜야 한다.
showTotalCars()는 단순히 이 값을 출력하는 메서드이므로, totalCars++를 여기에 넣으면 누적된 차량 수가 제대로 계산되지 않는다.