객체지향 프로그래밍
다양한 연산을 수행하는 계산기를 여러 개 구현하고자 할 때, 여러 개의 계산기를 각각 하나씩 세세하게 구현하는 것은 매우 비효율적이다. 따라서, 계산기들의 공통 속성을 뽑아내어 클래스로 만든 후 계산기의 개수가 추가될 때마다 객체를 손쉽게 만들어 내기 위해서 객체지향 프로그래밍이 필요하다.
객체
1
2
3
4
5
6
7
8
| class Animal{
}
public class Sample{
public static void main(String[] args){
Animal dog = new Animal()
}
}
|
- 위 코드와 같이, 껍데기뿐인 클래스 Animal을 이용해 dog라는 객체를 만들 수 있다.
- new는 객체를 생성할 때 사용하는 키워드
- dog는 객체, dog는 Animal의 인스턴스
객체 변수
1
2
3
4
5
6
7
8
9
10
11
| class Animal {
String name;
}
public class Sample {
public static void main(String[] args) {
Animal dog = new Animal();
System.out.println(dog.name); //null
}
}
|
- 객체 변수: Animal 클래스 내부에 변수를 추가한 것처럼, 클래스에 선언된 변수를 의미
- “인스턴스 변수, 멤버 변수, 속성”과 동일한 용어
- 객체.객체변수로 접근 가능
메소드
- 위에서 dog.name이 null로 나오는데, 이는 객체변수에 값이 할당되어 있지 않은 상태
- 메소드를 이용해 객체 변수에 값을 대입 가능
- 클래스 내에 구현된 함수를 의미
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| class Animal {
String name;
public void setName(String name) {
this.name = name;
}
}
public class Sample {
public static void main(String[] args) {
Animal dog = new Animal();
dog.setName("MONG");
System.out.println(dog.name); //MONG
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| class Animal {
String name;
public void setName(String name) {
this.name = name;
}
}
public class Sample {
public static void main(String[] args) {
Animal dog = new Animal();
dog.setName("MONG");
Animal cat = new Animal();
cat.setName("MEW");
System.out.println(cat.name); // MEW
System.out.println(dog.name); // MONG
}
}
|
객체 지향적
- 클래스에서 가장 중요한 부분은 객체 변수의 값이 독립적으로 유지된다는 점 (클래스의 존재 이유)
- 객체 지향적(Object Oriented)이라는 말의 의미도 결국 객체 변수의 값이 독립적으로 유지되기 때문에 가능한 것
(※ 객체 변수의 값은 공유되지 않지만 나중에 알게될 static을 이용하게 되면 객체 변수를 공유하도록 만들 수도 있다)
Call by value
- 메소드에 값을 전달하는 것과 객체를 전달하는 것에 큰 차이 존재
- 메소드로 객체를 전달할 경우 메소드에서 객체의 객체변수(속성) 값 변경 가능
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| class Updater {
void update(int count) {
count++;
}
}
class Counter {
int count = 0; // 객체변수
}
public class Sample {
public static void main(String[] args) {
Counter myCounter = new Counter();
System.out.println("before update:"+myCounter.count); // 0
Updater myUpdater = new Updater();
myUpdater.update(myCounter.count);
System.out.println("after update:"+myCounter.count); // 0
}
}
|
- 결과: 객체 변수 count의 값을 update메소드에 넘겨서 변경시키더라도 값에 변화가 없다.
- update 메소드는 값(int 자료형)을 전달받았기 때문
- 아래와 같이 update 메소드의 입력항목을 Counter counter와 같이 객체를 전달받도록 변경
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
| class Updater {
/*void update(int count) {
count++;
}*/
void update(Counter counter) {
counter.count++;
}
}
class Counter {
int count = 0; // 객체변수
}
public class Sample {
public static void main(String[] args) {
Counter myCounter = new Counter();
System.out.println("before update:"+myCounter.count); // 0
Updater myUpdater = new Updater();
myUpdater.update(myCounter); //myUpdater.update(myCounter.count);
System.out.println("after update:"+myCounter.count); // 1
}
}
|
참고자료
점프 투 자바 - 객체지향 프로그래밍