static 함수와 인스턴스 함수의 차이
/*-------------------
* static 키워드를 사용한 변수는 클래스가 메모리에 올라갈 때 자동으로 생성이 됩니다.
인스턴스 생성 없이 바로 사용이 가능한 것이죠.
이런 특성 때문에 프로그램 내에서 공통으로 사용되는 데이터들을 관리할 때 이용합니다.
자바 프로그램에서는 공통 로직이 들어가는 유틸 기능을 static 으로 작성하곤 합니다.
이런 static 은 남발해서는 안되며 공통으로 값을 유지하고 싶을 때만 사용합니다.
*/
public class StaticSample02 {
public static void main(String args[]) {
Card c1 = new Card();
c1.kind = "Heart";
c1.number = 7;
System.out.println("==> 인스턴스 함수 호출");
System.out.println("totalWidth() : " + c1.totalWidth());
System.out.println("==> static 함수 호출 ");
System.out.println("totalWidth() : " + Card.totalWidth(10, 20));
}
}
class Card {
String kind; // 카드 종류
int number; // 카드 숫자
int width = 10; // 카드 넓이
int height = 25; // 카드 높이
public int getNumber() {
return number;
}
public int totalWidth() {
return width * height;
}
public static int totalWidth(int width, int height) {
return width * height;
}
}
/*--------결과
==> 인스턴스 함수 호출
totalWidth() : 250
==> static 함수 호출
totalWidth() : 200
--------------------------------------*/