추상화 --> 클래스 --> 객체
예) class Television(클래스)
int channel (상태, 속성, 필드)
int volume
boolean onOff
---------------------------------------------------------------------------
public class Television { // 와플 틀 , 클래스
int channel;
int volume;
boolean onOff;
}
---------------------------------------------------------------------------
public class TelevisionTest { // 와플
public static void main(String[] args) {
Television tv = new Television(); // tv는 참조형 new를 해서 힙공간에 만들어진다. 3개의 필드를 가지고 있는다.
tv.channel = 7; // tv가 참조하는 객체로부터 채널이라는 필드로 접근
tv.volume = 9;
tv.onOff = true;
System.out.printf("텔레비전의 채널은 %d이고 볼륨은 %d입니다.", tv.channel, tv.volume);
}
}
public class TelevisionTest {
public static void main(String[] args) {
Television myTv = new Television(); // 객체
myTv.channel = 7;
myTv.volume = 9;
myTv.onOff = true;
System.out.printf("나의 텔레비전의 채널은 %d이고 볼륨은 %d입니다.\n", myTv.channel, myTv.volume);
Television yourTv = new Television(); // 객체
yourTv.channel = 10;
yourTv.volume = 5;
yourTv.onOff = true;
System.out.printf("너의 텔레비전의 채널은 %d이고 볼륨은 %d입니다.", yourTv.channel, yourTv.volume);
}
}
각 객체마다 별도의 변수(필드)를 가진다.
메소드는 입력을 받아서 처리결과를 반환하는 상자로 생각
예) int add(int x, int y) { // x, y는 매개변수(전달 값)이다. int add이니 리턴되는 x+y값이 정수(int)이다.
return x+y;
}
void는 반환값이 따로 없다. void 메소드 안에서 return;을 사용하면 그 메소드를 벗어난다.
return main;은 메인을 벗어나면 전체 프로그램이 종료된다
------------------------------------------------------------------------------
public class Television {
int channel; // 속성, 필드
int volume;
boolean onOff;
void print() {
System.out.printf("채널은 %d이고 볼륨은 %d입니다.\n", channel, volume); // 동작
}
}
------------------------------------------------------------------------------
public class TelevisionTest {
public static void main(String[] args) {
Television myTv = new Television();
myTv.channel = 7;
myTv.volume = 9;
myTv.onOff = true;
myTv.print();
Television yourTv = new Television();
yourTv.channel = 10;
yourTv.volume = 5;
yourTv.onOff = true;
yourTv.print();
}
}
---------------------------------------------------------------------------------
public class Television {
int channel;
int volume;
boolean onOff;
void print() {
System.out.printf("채널은 %d이고 볼륨은 %d입니다.\n", channel, volume);
}
int getChannel() { // 바로 속성에 접근하는 것보다 간접적으로 메소드를 통해 접근하는 것이 좋은 설계다. 보안 등의 이유
return channel;
}
}
public class TelevisionTest {
public static void main(String[] args) {
Television myTv = new Television();
myTv.channel = 7;
myTv.volume = 9;
myTv.onOff = true;
myTv.print();
int ch = myTv.getChannel();
System.out.println("현재 채널은 " + ch + "입니다.");
Television yourTv = new Television();
yourTv.channel = 10;
yourTv.volume = 5;
yourTv.onOff = true;
yourTv.print();
}
}
댓글 없음:
댓글 쓰기