Computer Science/컴퓨터 프로그래밍

Java OOP(Object Oriented Programming)

Chavo Kim 2020. 10. 1. 19:54

1. OOP란?

1-1. OOP의 정의

Programming을 Object들끼리 interaction하는 관점으로 프로그래밍을 하는 방법을 뜻한다.

 

이게 당최 무슨 소리냐?

 

우선 하나씩 바라보자.

 

object란 자바에서의 데이터들에 속하고,

 

Class라는 틀에 의해 만들어지는 제품이라고 생각하면 되겠다.

 

예를 들어 슈크림 붕어빵, 팥 붕어빵, 녹차 붕어빵(Object),,,,등등이 같은 붕어빵 틀(Class)에 의해 만들어지는 것처럼 다른 Java의 Object들도 하나의 Class에서 생성되게 된다.

 

1-2. Class의 특징

Class는 Attribute와 Method를 가진다.

 

Attribute는 Class의 Object들이 공유하는 특징들이고(예를 들면 student 클래스라면 학번, 나이, 성별, 이름 등등이 되겠지)

 

Method는 Class의 Object들이 공유하는 함수이다(예를 들면 student 클래스의 study(), getDrunk() 등등이 있겠지..?)

 

아래와 같이 클래스를 선언 가능하다.

 

class Car{

	//attributes
	int width = 100;
    String color = 'red'; 
    
    //constructor
    Car(int width, String color){
    	this.width = width;
        this.color = color;
    }
    Car(){
    	System.out.println("New Car!")
    }
    
    //method
    void printHello(){
    	System.out.println("Hello!")
    }
    
    int getWidth(){
    	return width;
    }
}

 

method와 attribute는 이해하기 쉽지만

constructor는 새로울텐데,

 

constructor는 초기에 class를 선언할 때 개입하는 method라고 생각하면 된다.

(반환형이 없다!)

 

this.~~~는 class 내부의 attribute와 method 내부의 지역변수가 같은 이름일 때, 해당 변수가 class 내부의 attribute임을 알려주는 문법이라고 생각하면 된다.

 

1-3. static members

static variable, static method는 class 내부에서 보관하는 attribute를 설정한다.

 

예를 들어 car class가 얼마나 선언됐는지, 전체 car들의 width 합은 어떤지를 저장하고 싶다고 하자.

 

이는 개별 개별의 object 내부에 저장할 수 없고 car class 자신이 관리를 해야 한다.

 

이를 static variable로 관리를 한다.

 

static member는 static 함수나 constructor에서 밖에 사용을 못하고,

 

해당 static method는 object를 만들지 않아도 사용이 가능하다.(마치 java.lang.Math)

 

class Car{
	static int num = 3;
    static int totalMile = 0;
    
    //static method는 static 변수만 선언 가능
    static void printNum(){
		System.out.println("The number of cars is " + num);
	}
    
    //constructor에서도 static variable을 선언 가능
    Car() { num++; }
    
    //일반 method에서도 static 변수 선언 가능
    void setMile(int mile){
    	this.mile = mile;
        totalMile += mile;
    }
}

Main Method

Car car1 = new Car(),
	car2 = new Car(),
    car3 = new Car();
    
car1.setMile(20);
car2.setMile(30);
car3.setMile(40);

//object 없이 선언 가능
Car.printNum();
System.out.println(Car.totalMile);

out

3
90

 

1-4. Object에서의 '=', '=='의 의미

 

Object에서 '=' 같은 주소값을 할당한다는 것을 의미한다.(해당 오브젝트의 값이 바뀌면 함께 바뀌게 된다.)

그리고 '=='는 주소값이 같은지 확인하는 operator

값이 같은지 확인하고 싶다면 'isequal()' method를 사용해야 한다.

 

String str1 = new String("hey");
String str2 = new String("hey");
String str3 = str1;

System.out.println(str1 == str2);
System.out.println(str1 == str3);

out

false
true

 

1-5. Call-by-Value & Call-by-Reference

swap 함수를 별도로 구현한다고 생각해보자

 

만약 아래와 같이 함수를 선언한다면

 

class Test{
	static void swap(int a, int b){
    	int temp;
        temp = a;
        a = b;
        b = temp;
    }
    
   	public static void main(String[] args){
    	int a = 2, b = 3;
        swap(a, b);
        System.out.println(a + " " + b);
    }
}

out

2 3

변화가 없는 것을 알 수 있다.

 

이는 바로 swap 함수에 a, b 변수를 받아갈 때 a, b의 값만 받아갔기 때문이다.

 

swap 함수를 통해 우리가 얻고자 하는 것이 뭔가?

 

a의 주소값에 b의 값을, b의 주소값에 a의 값을 배정하고 싶은 것 아닌가....

 

주소값을 어떻게 들고 가지..? (c++에도 비슷한 상황이 있지만 &을 사용하면 아주 간단하게,,,,Java는 너무 어렵다.)

 

 

아까 Object는 '=' 함수에서 주소값을 받아간다는 것이 기억나는가?

 

해당 int를 특정 class의 값으로 담아 놓으면 된다.

 

class Test{
	class IntHolder{
    	int value;
        IntHolder(int value){ this.value = value; }
    }
	
	static void swap(IntHolder a, IntHolder b){
        int temp = a.value;
        a.value = b.value;
        b.value = temp;
    }
    
   	public static void main(String[] args){
    	IntHolder a = new IntHolder(2), b = new IntHolder(3);
        swap(a, b);
        System.out.println(a.value + " " + b.value);
    }
}

out

3 2

우리가 원하는 결과가 나온다.