정적 메서드 및 정적 변수
정적 메서드(Static Methods)
정적 메서드
일반적인 메서드 처럼
new를 통해 객체를 만들지 않고. 즉, 호출 객체 없이 사용할 수 있는 메서드이다
특징: 특정 객체가 아닌 클래스 자체에 속한다. 정의는 클래스 내부에 작성된다
선언 방법: 메서드 헤더에 static 키워드를 추가한다
public static 반환타입 메서드이름(매개변수들) { ... }
호출 방법: 객체 이름 대신 클래스 이름을 직접 사용하여 호출한다
결과값 = 클래스이름.메서드이름(인자들);
예제
public class RoundStuff {
public static final double PI = 3.14159;
// 원의 면적을 계산하는 정적 메서드
public static double area(double radius) {
return (PI * radius * radius);
}
// 구의 부피를 계산하는 정적 메서드
public static double volume(double radius) {
return ((4.0 / 3.0) * PI * radius * radius * radius);
}
}실행 코드를 보면 RoundStuff 객체를 생성(new)하는 과정이 전혀 없다
RoundStuff.area(radius)RoundStuff.volume(radius)- 위와 같이 클래스명에 점(.)을 찍어 바로 기능을 사용하는 것이 정적 메서드의 가장 큰 특징이다
주의사항: Static 메서드 내에서 비정적 멤버 호출
정적 메서드를 사용할 때 가장 자주 마주치는 제약 사항이다
핵심 원칙: static 메서드는 클래스의 인스턴스 변수(필드)를 참조할 수 없으며, 비정적 메서드를 호출할 수 없다
이유: static 메서드는 객체 생성 없이 클래스 이름으로 호출된다. 따라서 this 파라미터가 존재하지 않는다. 반면 인스턴스 변수나 비정적 메서드는 ‘어떤 객체의 것인지’를 나타내는 this가 필요하다. 주인이 누구인지 알 수 없으니 사용할 수 없는 것이다
가능한 것: static 메서드 내에서 다른 static 메서드를 호출하는 것은 가능하다
예제 분석: main이 포함된 Temperature 클래스
import java.util.Scanner;
public class Temperature {
// 섭씨 온도를 저장하는 비공개 인스턴스 변수
private double degrees;
// 기본 생성자
public Temperature() {
degrees = 0;
}
// 매개변수가 있는 생성자
public Temperature(double initialDegrees) {
degrees = initialDegrees;
}
// 수정자 (Setter)
public void setDegrees(double newDegrees) {
degrees = newDegrees;
}
// 접근자 (Getter)
public double getDegrees() {
return degrees;
}
// 문자열 변환 메서드
public String toString() {
return (degrees + " C");
}
// 비교 메서드
public boolean equals(Temperature otherTemperature) {
return (degrees == otherTemperature.degrees);
}
/**
* 화씨 온도를 섭씨 온도로 변환하는 정적(static) 메서드
*/
public static double toCelsius(double degreesF) {
return 5 * (degreesF - 32) / 9;
}
// 프로그램 실행점 (main 메서드)
public static void main(String[] args) {
double degreesF, degreesC;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter degrees Fahrenheit:");
degreesF = keyboard.nextDouble();
// 1. 정적 메서드 호출 (같은 클래스 내부이므로 클래스명 생략 가능)
degreesC = toCelsius(degreesF);
// 2. 객체 생성 (인스턴스화)
Temperature temperatureObject = new Temperature(degreesC);
// 3. 인스턴스 메서드 호출 (객체 이름을 통해 호출)
System.out.println("Equivalent Celsius temperature is "
+ temperatureObject.toString());
}
}