개발공부/Java
(3) static, constant
klyhyeon
2020. 7. 4. 12:43
728x90
7/3 - static 변수/메서드 , constant(상수)
1. static
- 개요
> 변수나 메서드를 재선언하지 못하게 하는 기능
> 호출 시 규칙이 있음
> 아직 제대로 이해하진 못함
- 사용법
> Class 내 변수 생성 시 데이터 타입 앞에 static을 붙임
> Mainclass 호출 시 객체 생성하지 않아도 됨.
> 클래스를 앞에 쓰고 static 변수를 뒤에 붙여줌
public class LapTop {
system.out.println(LapTop.info); // [LapTop = Class, info = static]
}
2. constatnt
- 대문자로 표기해주며, 고정된 상수로 사용된다. 변경이 불가능하다.
- static, final과 함께 사용한다.
public class Earth {
static final double RADIUS = 6400;
static final double SURFACE_AREA;
static {
SURFACE_AREA = RADIUS * RADIUS * 4 * Math.PI;
}
public static void main(String[] args) {
System.out.println("지구의 반지름: " + Earth.RADIUS + "km");
System.out.println("지구의 표면적: " + Earth.SURFACE_AREA + "km^2");
}
}