정적 변수 사용하기
Pizza02.java
package ex05;
public class Pizza02 {
private String toppings;
private int radius;
static final double PI = 3.141592;
static int count = 0;
public Pizza02(String toppings) {
this.toppings = toppings;
count++;
}
}
Pizza02Test .java
package ex05;
public class Pizza02Test {
public static void main(String[] args) {
Pizza02 p1 = new Pizza02("Super Supreme");
Pizza02 p2 = new Pizza02("Cheese");
Pizza02 p3 = new Pizza02("Pepperoni");
int n = Pizza02.count;
System.out.println("지금까지 판매된 피자 개수 = " + n);
}
}
정적 메소드 사용하기
MyMath.java
package ex05;
public class MyMath {
public static int abs(int x) {
return x > 0 ? x : -x;
}
public static int power(int base, int exponent) {
int result = 1;
for (int i = 0; i <= exponent; i++) {
result *= base;
}
return result;
}
}
MyMathTest.java
package ex05;
public class MyMathTest {
public static void main(String[] args) {
System.out.println("10의 3승은 " + MyMath.power(10, 3));
}
}
정적 메소드 사용하기 2
//정적 메소드만을 이용하여 작성한 세제곱 계산
package ex05;
public class Test {
public static int cube(int x) {
int result = x * x * x;
return result;
}
public static void main(String[] args) {
System.out.println("10*10*10은 " + cube(10));
}
}
정적 블록
정적 블록(static block)은 클래스가 메모리에 로드될 때 한 번만 실행되는 문장들의 집합이다.
일반적으로 정적 변수들을 초기화 하는 용도로 많이 사용된다.