Language/JAVA
[JAVA 객체] 자바의 정석 06장. 객체지향 프로그래밍(1) - 예제
도도고영
2022. 1. 8. 14:47
예제1번) Tv인스턴스를 저장하는 참조변수 t1과 t2를 선언한 후, t1에 있는 객체의 주소를 t2에 저장하는 코드이다.
class Tv {
//Tv의 속성(멤버변수)
String clolr; //색상
boolean power; //전원 상태
int channel; //채널
//Tv의 기능(메서드)
void power() {power = !power;} //Tv를 켜거나 끄는 기능을 하는 메서드
void channelUp() {++channel;} //Tv의 채널을 높이는 기능을 하는 메서드
void channelDown() {--channel;} //Tv의 채널을 낮추는 기능을 하는 메서드
}
class TvTest3{
public static void main(String[] args) {
Tv t1 = new Tv();
Tv t2 = new Tv();
System.out.println("t1의 channel값은 " + t1.channel + "입니다.");
System.out.println("t2의 channel값은 " + t2.channel + "입니다.");
t2 = t1; //t1이 저장하고 있는 값을 t2에 저장한다.
t1.channel = 7;
System.out.println("t1의 channel값을 7로 변경하였습니다.");
System.out.println("t1의 channel값은 " + t1.channel + "입니다.");
System.out.println("t2의 channel값은 " + t2.channel + "입니다.");
}
}
예제2번) 객체를 배열에 담아 사용하는 예제이다. 예제 1번의 Tv클래스를 사용한다.
class TvTest4{
public static void main(String[] args) {
Tv[] tvArr = new Tv[3]; //길이가 3인 Tv객체 배열
for (int i = 0; i < tvArr.length; i++) {
tvArr[i] = new Tv();
tvArr[i].channel = i + 10;
}
for (int i = 0; i < tvArr.length; i++) {
tvArr[i].channelUp();
System.out.printf("tvArr[%d].channel=%d\n", i, tvArr[i].channel);
}
}
}
예제3번) 참조형 변수를 메서드의 매개변수로 받는 예제이다.
public class ReferenceParamEx2 {
public static void main(String[] args) {
int[] x = {10};
System.out.println("main():x = " + x[0]);
change(x);
System.out.println("After change(x)");
System.out.println("main():x = " + x[0]);
}
static void change(int[] x) {
x[0] = 1000;
System.out.println("change():x = " + x[0]);
}
}