class Variables { // 1. 클래스 영역
int iv; // ① 인스턴스 변수
static int cv; // ② 클래스변수(static변수, 공유변수)
void method() { // 2. 메서드 영역
int lv = 0; // ③ 지역변수
}
}
변수의 종류 | 선언 위치 | 생성 시기 |
---|---|---|
클래스변수 (Class Variable) |
클래스 영역 | 클래스가 메모리에 올라갈 때 (클래스가(설계도가) 필요할때) 객체생성X 아무때나 사용 가능 |
인스턴스 변수 (Instance Variable) |
클래스 영역 | 인스턴스가 생성되었을 때 (객체-iv 묶어 놓은것-생성) 객체생성O 객체생성을 해야 사용 가능 |
지역변수 (Local Variable) |
클래스 영역 이외의 영역 (메서드, 생성자, 초기화 블럭 내부) |
변수 선언문이 수행되었을 때 (메서드가 호출 되었을 때, 메서드 종료시 자동 제거) |
- 인스턴스 변수는 인스턴스가 생성될 때마다 생성되므로 인스턴스마다 각기 다른 값을 유지할 수 있지만, 클래스 변수는 모든 인스턴스가 하나의 저장공간을 공유하므로, 항상 공통된 값을 갖는다.
속성 | 무늬 | 인스턴스 변수 개별 속성 |
---|---|---|
숫자 | ||
폭 | 클래스 변수 공통 속성 |
|
높이 | ||
기능 | ... |
class Card {
String kind; // 무늬 (iv : 개별속성)
int number; // 숫자 (iv : 개별속성)
static int width = 100; // 폭 (cv : 공통속성)
static int height = 250; // 높이 (cv : 공통속성)
}
Card c = new Card(); // 객체생성
c.kind = "HEART"; // 객체사용
c.number = 5;
c.width = 200; // 동작은 함 하지만 cv는 이렇게 사용하는건 권장하지 않음
c.height = 300; //
// cv를 사용할때는 클래스 이름을 쓰고 변수명을 선언하는것이 바른 사용법
Card.width = 200;
Card.height = 300;
public class Ex6_3 {
public static void main(String[] args) {
// cv 자동으로 만들어짐
// 객체생성 없이 사용 가능
System.out.println("Card.width = " + Card.width); // Card.width = 100
System.out.println("Card.height = " + Card.height); // Card.height = 250
// cv가 만들어진 이후에 객체 생성
Card c1 = new Card();
c1.kind = "Heart";
c1.number = 7;
Card c2 = new Card();
c2.kind = "Spade";
c2.number = 4;
System.out.println("c1은 " + c1.kind + ", " + c1.number + "이며, 크기는 (" + c1.width + ", " + c1.height + ")");
System.out.println("c2는 " + c2.kind + ", " + c2.number + "이며, 크기는 (" + c2.width + ", " + c2.height + ")");
System.out.println("c1의 width와 height를 각각 50, 80으로 변경합니다.");
// c1.width = 50;
// c1.height = 80;
Card.width = 50; // 위에처럼 쓰면 c1만 바뀐다고 오해함
Card.height = 80; // width, height는 cv이기 때문에 클래스 이름으로 접근해야 iv와 혼동되지 않는다.
System.out.println("c1은 " + c1.kind + ", " + c1.number + "이며, 크기는 (" + c1.width + ", " + c1.height + ")");
System.out.println("c2는 " + c2.kind + ", " + c2.number + "이며, 크기는 (" + c2.width + ", " + c2.height + ")");
}
}
class Card {
String kind;
int number;
static int width = 100;
static int height = 250;
}