static 자료형 참조변수; => static변수
자료형 참조변수; => instance변수
instnace 변수
클래스 변수선언의 가장 큰 목적은 공유할 때
2개의 instance 변수,2개의 static(클래스)변수_4개의 멤버변수
메모리 각각 할당(개별)
static 변수
클래스변수-같은 클래스의 모든 instance들이 공유
instance 생성 없이 클래스이름.클래스변수명으로 접근
클래스가 로딩될때 생성/종료하면 소멸
메모리 하나만 할당(공유)
package day0627; //main과 연결되려면 하나는 메인이 없고 하나는 메인 있어야함 //메인은 하나만 있어야하니까
//연결된 것들을 하나의 페이지에 표시 가능한데 이때 public은 하나만 생성가능
//멤버 만들기용 클래스
public class Ex2Object_02 {
//static이 안 붙으면 무조건 instance 변수
//클래스 변수선언의 가장 큰 목적은 공유할 때
//2개의 instance 변수,2개의 static(클래스)변수_4개의 멤버변수
//메모리 각각 할당(개별)
String kind; //카드의 무늬
int number; //카드의 숫자
//클래스변수-같은 클래스의 모든 instance들이 공유
//instance 생성 없이 클래스이름.클래스변수명으로 접근
//클래스가 로딩될때 생성/종료하면 소멸
//메모리 하나만 할당(공유)
static int width; //카드의 폭
static int height; //카드의 높이
}
instance변수 호출
클래스명 변수명=new 클래스명();
System.out.println(변수명.kind); //null
System.out.println(변수명.number); //0
//값 주기
변수명.kind="Heart";
변수명.number=4;
//값을 주어서 값 출력
System.out.println(card1.kind);
System.out.println(card1.number);
static변수 호출
//값을 안줘서 0출력
System.out.println(클래스명.width);
System.out.println(클래스명.height);
//클래스변수
Ex2Object_02.width=10;
Ex2Object_02.height=20;
package day0627;
//public은 1페이지에 단 1개만 가능
public class Ex2Main_02 {
public static void main(String[] args) {
//static
//값을 안줘서 0출력
System.out.println(Ex2Object_02.width);
System.out.println(Ex2Object_02.height);
//클래스변수
Ex2Object_02.width=10;
Ex2Object_02.height=20;
//값을 줘서 값 출력
System.out.println(Ex2Object_02.width);
System.out.println(Ex2Object_02.height);
//instance
//instance 생성 후 변수 호출 가능
Ex2Object_02 card1=new Ex2Object_02();
//2개 다 값을 안줘서 null/0 출력
System.out.println(card1.kind); //null
System.out.println(card1.number); //0
//값 주기
card1.kind="Heart";
card1.number=4;
//값을 주어서 값 출력
System.out.println(card1.kind);
System.out.println(card1.number);
//instance 변수 다시 생성 후 멤버값 변경 후 출력
Ex2Object_02 again=new Ex2Object_02();
again.kind="Clover";
again.number=10;
System.out.println(again.kind);
System.out.println(again.number);
}
}
package day0627; //멤버용 클래스
public class Student_03 {
String name;
int age;
static String schoolName; //static은 공유할 때 주로 사용
}
package day0627;
public class StudentMain_03 {
public static void main(String[] args) {
//instance 변수는 1,2,3...등등 늘어날 수 있음
Student_03 stu1=new Student_03();
Student_03 stu2=new Student_03();
stu1.name="최성현";
stu1.age=25;
stu2.name="박영주";
stu2.age=22;
//static 변수
Student_03.schoolName="쌍용고등학교";
System.out.println("**클래스 멤버값 출력**");
System.out.println("학교명: "+Student_03.schoolName);
System.out.println("학생1정보");
System.out.println("이름: "+stu1.name+", 나이: "+stu1.age);
System.out.println("학생2정보");
System.out.println("이름: "+stu2.name+", 나이: "+stu2.age);
}
}