/ JAVAJUNGSUK

Ch6-12~13. 변수

자바의 정석 기초편

0. 목차



Chapter6. 객체지향 프로그래밍Ⅰ

Ch6 - 12. 클래스 변수와 인스턴스 변수

Ch6 - 13. 클래스 변수와 인스턴스 변수 예제



Ch6 - 12. 클래스 변수와 인스턴스 변수


▶ 클래스 변수와 인스턴스 변수의 차이점

▷ 공통 속성 : 클래스 변수(cv)
▷ 개별 속성 : 인스턴스 변수(iv)
class Card {
    // 개별 속성 : iv
    String sign; // 기호
    int number; // 숫자
    
    // 공통 속성 : cv
    static int width = 100; // 폭;
    static int height = 230; // 높이;
}


▶ 클래스 변수와 인스턴스 변수의 사용 방법

▷ 객체 생성
Card c = new Card();
▷ 객체 사용
  • 인스턴스 변수(iv)
      c.kind = "HEART";
      c.number = 5;
    
  • 클래스 변수(cv)
      Card.width = 200;
      Card.height = 300;
    



Ch6 - 13. 클래스 변수와 인스턴스 변수 예제


▶ 카드의 공통 속성(cv), 개별 속성(iv) 활용

▷ 코드
class Ex6_3 {
	public static void main(String args[]) {
		System.out.println("Card.width = " + Card.width);
		System.out.println("Card.height = " + Card.height);

		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으로 변경합니다.");
		Card.width = 50;
		Card.height = 80;

		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;
}

// console
Card.width = 100
Card.height = 250
c1 Heart, 7이며, 크기는 (100, 250)
c2 Spade, 4이며, 크기는 (100, 250)
c1 width height 각각 50, 80으로 변경합니다.
c1 Heart, 7이며, 크기는 (50, 80)
c2 Spade, 4이며, 크기는 (50, 80)
▷ 그림 그려보며 cv, iv 생각하기