본문 바로가기
java

0927_클래스, 변수

by 신방동불주먹 2022. 9. 27.

클래스:  필드(변수)와 메소드로 구성

 

 

  • Main class 는 한 개만 존재, 동작만 구현(객체생성 = 인스턴스 생성)

ex) 배열의 최대값을 구하고 싶다 -> 다른 class에서 (객체를 표현) 구현 후 실행만 main class에서 함

 

  • 멤버변수(자동초기화) : 1) 인스턴스 변수 : int age(객체변수?)
                                          2) static(클래스)변수 : static (제어자) int size
                                             -생성없이 사용가능하다.
                                            -공유되어진다. 메모리에 매번 할당x 별도의 메모리에 한번만 할당되어 여러 객체가 같은 데                                           이터를 공유. 

                                               -멤버변수는 자료형의 기본값으로 자동 초기화. 따라서 초기화 없이 사용 가능.

  • 지역변수(강제초기화)

public class TvTest {//0927

		//int sum; //멤버변수 : 클래스 단위 변수
		
	public static void main(String[] args) { //객체 생성은 main 클래스에서 한다.
		//블록단위가 클래스 영역에서 선언되는 변수 = 전역(멤버)변수 (Tv클래스의 멤버변수 는 사용할 수 없음)
		
	//	int sum =0; //지역변수 
	//	sum += 10; //연산 전 무조건 초기화가 되어있어야 함.
		
		
//		new Tv(); //메모리로 할당되어진 tv가 가진 멤버변수, 함수의 첫번째 주소값을 가짐.
		
		//참조연산자 : . 
//		new Tv().power = true; //Tv클래스 안에 있는 변수를 .연산자를 통해 참조
//		new Tv().channel = 10; //new 수만큼 Tv 수가 생성되는 것. 
		//이렇게 되면 각 다른 Tv가 만들어지는 것. 

		 Tv t = new Tv(); //만들어진 클래스를 타입으로 선언하고 변수명 넣음 : 참조변수(==주소값)
		//생성된 객체의 주소값을 가져오려면
	 	t.power = true; //참조변수.메소드
	 	t.channel = 10;
	 	//System.out.println(t.channel);
	 	t.ChannelDown(); //메소드 참조
		System.out.println(t.channel);
		
		Tv t2 = new Tv();//객체를 생성할 때마다 물리적으로 완전히 다른 주소값을 가지고 있음. 새로운 객체
		t2.channel = 20;
		System.out.println(t.channel);
		System.out.println(t2.channel);
		t2.ChannelDown();

		//t2 = t : t의 참조변수의 주소값을 t2에 넣는 경우 기존 t2의 메모리를 삭제 해주어야함 : garbage collection
		//치환되는 조건 : 두 참조변수의 타입이 동일한 경우만 가능
		t2=t; 
		System.out.println(t.channel);
		System.out.println(t2.channel);
		t.ChannelDown();
		System.out.println(t.channel);
		System.out.println(t2.channel);
		
		
		
	}

}
  • main class 에서 클래스 객체 활용:

Tv tv; Tv 객체에 대한 레퍼런스 변수 선언 (Tv객체에 대한 주소값)

tv = new Tv(); new 연산자를 이용한 Tv 객체 생성 --> 객체 메모리에 할당

tv.channel; (.)연산자를 이용한 Tv의 channel 필드에 접근

public class Tv {
	//속성(변수) : 크기, 전원버튼, 채널, 볼륨 , 색상, 모델, 제조사, 제조년도  등
	
	//기능(메소드) : on/off, 채널 up/down, 볼륨 up/down

	//class의 멤버변수는 기본값으로 초기화가 되어있다. 따라서 초기화 없이 사용 가능하다.
	boolean power; //전원버튼  0
	int channel; //채널           0
	int volumn;//볼륨              0
	String color; //색상         null
	String model; //모델
	int year;  //제조년도
	String company; //제조사
	
	
	//on/off, 채널 up/down, 볼륨 up/down 구현
	//메소드 구현
	void Power() { //전원 on/off
		power = !power; //true->false, false->true; 반대상태로 바뀌어 버리게
	}
	
	void ChannelUp() { //채널 up버튼
		channel++;
	}
	
	void ChannelDown() { //채널 down버튼
		channel--;
	}
	
	void volumnUp() {//채널 Up버튼
		volumn++;
	}
	
	void volumnDown() {//채널 down버튼
		volumn--;
	}

	//tv를 소개하는 메소드
	
	void showInfo() {
		System.out.println(model);
		System.out.println(year);
		System.out.println(company);
	}
	
}
  • 객체 배열 : 객체 배열에 대한 레퍼런스를 원소로 갖는 배열

Time[] t1; Time 클래스의 배열에 대한 레퍼런스 변수를 t1에 선언

t1 = new Time[5]; Time 객체에 대한 레퍼런스 5개 생성

for(int i=0;i<t1.length;i++){

time[i] = new Time(); 배열 t1 길이만큼 객체 생성 

 

 

public class TimeTest {

	public static void main(String[] args) {
		Time t1, t2, t3; //변수 선언
//		Time t1 = new Time
		

//		t1 = new Time(); //동일한 작업 하는데 걸린시간
//		t1.hour = 10;
//		t1.minute = 29;
//		t1.second = 33;
//		
//		t2 = new Time();
//		t2.hour = 3;
//		t2.minute = 45;
//		t2.second = 11;
//		
//		t3 = new Time();
//		t3.hour = 5;
//		t3.minute = 15; 
//		t3.second = 53;
		
		
		Time[] time = new Time[3]; //참조형 변수를 사용하여 배열생성
		
		for(int i=0;i<time.length;i++) { //객체 한번에 생성
			time[i] = new Time();
		}
		
		//time[0] = new Time(); //인덱스 0번째에 객체 생성
		time[0].hour = 10;
		time[0].minute =29;
		time[0].second =33;
		
		//time[1] = new Time();//인덱스 1번째에 객체 생성
		time[1].hour = 3;
		time[1].minute = 45;
		time[1].second = 11;
	
		//time[2] = new Time();//인덱스 2번째에 객체 생성
		time[2].hour = 5;
		time[2].minute = 15;
		time[2].second = 53;
	
	
		// x시x분x초로 출력
		//1
		for(int i=0;i<time.length;i++) {
			System.out.println(time[i].hour + "시" + time[i].minute+"분"+time[i].second+"초");
			
		}System.out.println();
	
		//2
		for(Time t : time) { //배열 time의 길이만큼 반복 (Time 클래스자료형)
			System.out.println(t.hour + "시" + t.minute+"분"+t.second+"초");
		}
	
	}

}
public class Time {
	//시, 분, 초
	
	int hour;
	int minute;
	int second;

}
public class CartTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

//	System.out.println(Card.cv); //스태틱변수는 생성없이 클래스명으로 참조가 가능하다.
//								//c1으로 생성되기 전 메모리에 할당된다.
//	
//	Card c1 = new Card();
//	c1.iv = 10;
//	
//	
//	Card c2 = new Card();
//	c2.iv = 20;
//	
//	//인스턴스 변수인 iv는 각각 별도의 값을 가짐
//	System.out.println("c1.iv : "+c1.iv);
//	System.out.println("c2.iv : "+c2.iv);
//	
//	System.out.println("c1.cv : "+c1.cv);
//	System.out.println("c2.cv : "+c2.cv);
//	
//	//스태틱변수의 값은 공유 된다. 
//	c1.cv = 80;
//	
//	System.out.println("c1.cv : "+c1.cv);
//	System.out.println("c2.cv : "+c2.cv);
//	
//	c2.cv = 200;
//	System.out.println("c1.cv : "+c1.cv);
//	System.out.println("c2.cv : "+c2.cv);
//	
//	
	
		Card c1 = new Card();
		c1.number = 1;
		c1.kind = "heart";
	
		Card c2 = new Card();
		c2.number = 3;
		c2.kind = "spade";
		
		System.out.println(c1.number);
		System.out.println(c1.kind);
		
		System.out.println(c2.number);
		System.out.println(c2.kind);
		
		System.out.println(Card.height);
		System.out.println(Card.width);
	}

}

static 변수는 main 메소드 실행 전 이미 생성.

static 변수를 포함한 객체 생성 전 class명으로 사용 할 수 있다.

카드의 크기는 모두 똑같아야 한다 : 같은 너비와 높이를 가져야 한다. -->static 으로 선언.


public class Card {

	//속성
	//멤버변수(자동초기화)  : 1)인스턴스 변수 - int age(객체변수?)
	//클래스 안에 정의된 변수    2)스태틱(클래스)변수 - static (제어자) int size
	//						생성없이 사용가능하다. (new를 이용한 생성)		
//	//						공유되어진다. 메모리에 매번 할당x 별도의 메모리에 한번만 할당되어 여러 객체가 같은 데이터를 공유함.
//	int iv; //인스턴스변수
//	static int cv = 100; //static변수 필요에 따라 선언과 동시에 초기화 해서 사용 가능
//
//	//지역변수(강제초기화) :메소드 내에서 쓰는 변수
//	void channel() {
//		int x;
//	}


	//속성 : 숫자, 모양, 크기(높이, 너비), ....
	int number;
	String kind;
	static int height = 100; //동일
	static int width = 80;	//동일
	






}

 

'java' 카테고리의 다른 글

0928_참조형 변수 (클래스 타입), 기본형 변수  (0) 2022.09.28
0928_메소드  (0) 2022.09.28
0927_이중배열(빙고게임)  (0) 2022.09.27
0926_이중배열  (0) 2022.09.26
0922_배열  (0) 2022.09.22