클래스(Class)
객체를 정의해 놓은 것. 객체를 생성하는데 사용함 객체를 모델링 하는 도구
객체(Object)
클래스에 정의된 것을 토대로 메모리에 할당받은 공간. 값 부여받진 않음
class | Object |
제품 설계도 | 제품 |
TV 설계도 | TV |
붕어빵 기계 | 붕어빵 |
인스턴스(Instance)
객체생성에 의해 메모리(Heap 영역)에 생성된 인스턴스
클래스로부터 객체를 만드는 과정을 클래스의 인스턴스화(실체화, instantiate)라고 함
구성
속성
멤버 변수(member variable)
특성(attribute)
필드(field)
상태(state)
기능
메서드(method)
함수(function)
행위(behavior)
예시
import java.lang.reflect.Field;
public class TV {
String color;
boolean power;
int channel;
void power() {
power = !power;
}
void channelUp() {
++channel;
}
void channelDown() {
--channel;
}
public TV(Object... obj) throws IllegalAccessException {
// 단순 this 삽입
this.color = (String) obj[0];
this.power = (boolean) obj[1];
this.channel = (int) obj[2];
// reflection 사용
Field[] fields = this.getClass().getDeclaredFields();
for (int i = 0; i < obj.length; i++) {
fields[i].set(this, obj[i]);
}
// instanceof 사용
for (Object o : obj) {
if (o instanceof String s) {
this.color = s;
} else if (o instanceof Boolean b) {
this.power = b;
} else if (o instanceof Integer i) {
this.channel = i;
}
}
}
}
import java.lang.reflect.Field;
public class TVTest {
public static void main(String[] args) throws Exception {
TV tv; // object
tv = new TV("yellow", false, 7); // instance
callObjStats(tv);
tv.color = "blue";
tv.power();
tv.channelUp();
tv.channelDown();
tv.channelDown();
callObjStats(tv);
}
static <T> void callObjStats(T v) throws Exception {
StringBuilder sb = new StringBuilder();
Field[] fields = v.getClass().getDeclaredFields();
for (var field : fields) {
var value = field.get(v);
sb.append(field.getName()).append('\t').append(value).append('\n');
}
System.out.println(sb);
}
}
color yellow
power false
channel 7
color blue
power true
channel 6