전체 코드
public class CardTest {
public static void main(String[] args) {
//static 멤버는 클래스 이름으로 접근이 가능함
Card.width = 200;
Card.height = 300;
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 + ")");
c1.width = 50;
c1.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 + ")"); //이렇게 하면 c2도 같이 변경되어 있는걸 확인할 수 있음 -> width, heigth는 static 변수라서 한 클래스에서 공통으로 사용하기 때문에 같은 변수 사용하는 것과 같다.
}
}
class Card{
//static 멤버
public static int width = 100;
public static int height = 250;
//인스턴스 멤버
public String kind;
public int number;
}
세부설명
static 맴버 값 입력
Card.width = 200;
Card.height = 300;
인스턴스 맴버 값 입력
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 + ")");
c1 클래스의 static 맴버 값 변경
c1.width = 50;
c1.height = 80;
c1 클래스의 값만 변경했지만 c2클래스 내에 있는 변수를 호출해도 변경된 결과값으로 출력됨
System.out.println("c1은 " + c1.kind + ", " + c1.number + "이며, 크기는 (" + c1.width + ", " + c1.height + ")");
System.out.println("c2은 " + c2.kind + ", " + c2.number + "이며, 크기는 (" + c2.width + ", " + c2.height + ")");
'JAVA' 카테고리의 다른 글
JAVA(19) - 생성자/기본 생성자/메소드 오버로딩/Method Overloading/ (0) | 2020.03.18 |
---|---|
JAVA(18) - 콜백함수/(STATIC/인스턴스)메소드에서 호출 (0) | 2020.03.17 |
JAVA(16) - 객체(object) /객체지향/객체 지향의 4대 특성/Class/Class 실습/필드의 초기화/메소드/변수의 종류/클래스맴버/인스턴스맴버/패키지 (0) | 2020.03.16 |
JAVA(15) - (0) | 2020.03.12 |
JAVA(14) - 가계부 만들어보기 (1) | 2020.03.11 |