💡 Static, Final 정의
📘 모든 객체가 함께 사용하는 변수나 메서드
Static 특징
Static 예제 코드
// static 변수 및 메서드가 포함된 class
public class Car {
static int numberOfCars = 0; // static 변수 (클래스 변수)
String model;
Car(String model) {
this.model = model;
numberOfCars++; // 객체가 생성될 때마다 증가
}
static void showTotalCars() { // static 메서드 (클래스 메서드)
System.out.println("총 차량 수 : " + numberOfCars);
}
}
//main 에서 각각의 객체 생성
public class TestStatic {
public static void main(String[] args) {
Car car1 = new Car("Avante");
Car car2 = new Car("Sonata");
Car.showTotalCars(); // 객체 없이 클래스 이름으로 호출 가능
}
}
//총 차량 수 : 2
📘 값 변경 불가 또는 참조 변경 불가
public class FinalExample {
final int MAX_SPEED = 120; // final 변수 (상수)
final void display() { // final 메서드 (오버라이드 금지)
System.out.println("최고 속도는 " + MAX_SPEED + "km/h 입니다.");
}
}
// final class Car {} // 만약 클래스에 final 붙이면 상속 불가
public class TestFinal {
public static void main(String[] args) {
FinalExample example = new FinalExample();
example.display();
// ex.MAX_SPEED = 150; -> 오류! final 변수는 값 변경 불가
}
}
static 과 함께 쓰일 때
public class Constants {
public static final double PI = 3.14159;
public static final String IU= "Jieun";
}