본문 바로가기

JAVA

[Java] 2-1강 - 객체 지향 프로그래밍 1 (Encapsulation - Access Modifier)

1. Object-Oriented language 기본 개념

1) Object

대부분의 variable과 literal는 object이다.

object : class의 instance (class는 object의 type이라고 봐도 된다.)

object type
instance  class
// Lecture.java

class Employee {
	String name;	
	public void setName(String name) {
		this.name = name;
	}
	public String getName() {
		return name;
	}
}

public class Lecture {
	public static void main(String[] args) {
		Employee m = new Employee();
		m.setName("Peter");
		System.out.println(m.getName());
	}
}

→ m이라는 instance를 Employee라는 class로 만든다.

→ m이라는 object의 type은 Employee이다.

 

2) Class

1> public class

public class의 이름이 곧 .java파일의 이름이 된다.

1개의 .java 파일에는 1개의 public class만 있을 수 있다. (일반 class는 여러개 있을 수 있다.)

public class는 main method를 가집니다. (main method는 program의 시작이 됩니다.)

 

cf> complie

.java 파일(source file)을 complie하면 .class 파일(byte code)이 된다.

(source file을 javac을 이용해서 complie하면 byte code가 되고 complier를 JDM이라는 virtual machine으로 실행)

 

2> variable & method

 

3) Instance Variable

(class 내부에) static keyword 없이 정의된 variable

다른 instance에서 instance variable을 만들었다면 이들은 독립적인 관계이다.

 

4) Access modifier

variable에 대한 접근 권한

1> public : 다른 class에서도 접근이 가능하다.

2> protected : [1] subclass (다른 package에서도 접근 가능)와 [2] 같은 package 내부의 class에서 접근할 수 있다.

3> 아무것도 없다면 : 같은 package 내의 class에서만 접근 가능

4> private: class에서만 접근 가능하다.

// example.java

package sogangcse;

class Employee {
	String name;
}

public class Lecture {
	public static void main(String[] args) {
		Employee m = new Employee();
		m.name = "Peter";
		System.out.println(m.name);
	}
}

예제는 default access modifier를 사용 (같은 package내의 class에서 접근 가능하다.)

- "peter"는 Employee와 같은 class에 있으므로 바로 접근이 가능하다. (이렇게 바로 대입이 가능하다.)

- 하지만 private을 쓰면 Employee와 "peter"는 같은 class에 있지 않으므로 접근이 불가능하다.

 

5) Method

1> Method header

- 마찬가지로 access modifier가 4가지 존재한다. (public, protected, default, private)

- method naming convention : 2번째 단어부터 대문자로

2> Method body

- this : object 그 자체를 의미

 

cf> Encapsulation

Class 내부에서 필요한 것은 접근 가능하게 하고, 나머지는 숨긴다.

기본적으로 협업을 하게 되면, 모두가 내 class의 member에 모두 접근할 수 있는 게 error를 만들 수 있다.

 

6) Constructor 

1> 객체 생성

Employee m = new Employee();

- 괄호가 붙는 것은 object가 만들어짐과 동시에 class의 contructor를 호출하기 때문이다.

- contructor를 정의하지 않은 경우 default constructor를 호출한다. (그래서 모든 class는 constructor를 가지고 있다.)

 

2> delete an object?

Java는 automatic garbage collection으로 object가 참조되지 않는 경우(메모리를 가리키지 않을 때) memory를 dellocate한다.

3> contructor의 조건

- contructor의 이름은 class 이름과 같아야 한다.

- contructor는 return하지 않아야 한다.

 

4> method overriding (contructor)

argument를 다르게 해서 constructor를 추가하면 조건에 맞는 constructor가 호출된다.

그러므로 method overriding을 하려면 constructor argument를 각각 다르게 해야 한다. 

class Employee {
	private String name;
	public Employee() {
		this.name = "NoName";
	}
	public Employee(String name) {
		this.name = name;
	}
	public String getName() {
	return this.name;
	}
}

5> contructor 내부에서 constructor를 호출하고 싶을 때 this로 호출할 수 있다.

class Employee {
	private String name;
	
    public Employee() {
	this("NoName");
	}

	public Employee(String name) {
		this.name = name;
	}

public String getName() {
	return this.name;
	}
}

2. Object-Oriented language 심화 개념

1) 객체를 array 형태로 여러 개 만들 수 있다.

1> 몇 개의 원소를 가질지 결정하고서

2> 각 원소별로 instance를 만든다.

class Employee {
	private String name;
	public Employee(String name) {
		this.name = name;
	}
	public String getName() {
		return this.name;
	}
}

public class Lecture {
	public static void main(String[] args) {
		Employee m[] = new Employee[3];
		m[0] = new Employee("Mario");
		m[1] = new Employee("Luigi");
		m[2] = new Employee("Toad");
		System.out.println(m[0].getName());
	}
}

2) instance variable

1> contructor 말고 class에서 instance variable에 값을 할당해줄 수 있다.

class Employee {	
	private String name = "Joe";
	public void setName(String name) {
		this.name = name;
	}
	public String getName() {
		return this.name;
	}
}

2> intialize를 하지 않아도 default value로 할당된다. 

numbers: 0, boolean: false, objects: null

(하지만 local variable은 initialize하지 않으면 error가 발생한다.)

 

3> final (keyword)

contructor에서만 값을 설정할 수 있다. (다른 method에서의 값을 변경할 수 없다.)

 

3) static variable

0> instance variable은 각 instance별로 독립적이다.

1> static variable

class에 소속되어 있지만 class의 instance에는 소속되지 않는다.

즉, 모든 instance가 "공유"하고 있다.

class Employee {	
	private static int lastId = 0;
	private int id;
	public Employee() { id = ++lastId; }
	public int getId() { return this.id; }
	public int getLastId() { return this.lastId; }
}

public class Lecture {
	public static void main(String[] args) {
		Employee m = new Employee(); 		// id = 1
		Employee n = new Employee(); 		// id = 2
		System.out.println(m.getId());		// this.id = 1
		System.out.println(n.getId());		// this.id = 2
		System.out.println(m.getLastId()); 	// this.lastId = 2
		System.out.println(n.getLastId());	// this.lastId = 2
	}
}

2> static variable의 initialize

- 선언할 때 initialize 할 수도 있고 (하지만 constructor에서 initialze하면 안 된다. object가 만들어질 때마다 초기화 되니까)

- static initialization block을 만들어서 initalize 할 수도 있다.

 

3> static final variable 

public class Math {
	public static final double PI = 3.14159265358979323846;
}
public class Lecture {
	public static void main(String[] args) {
		System.out.println(Math.PI);
	}
}

- final : 다른 사람(method)이 PI 값을 바꾸지 못하게 하려고

- static : 굳이 object 만들 필요 없이 PI 값을 쓰려고

 

4) Static Method

 

...

 

'JAVA' 카테고리의 다른 글

[Java] 4-1강 - 예외 처리  (0) 2020.11.17
[Java] 2-3강 - 객체 지향 프로그래밍 3 (Abstraction - Interface)  (0) 2020.10.16
[Java] 1-5강 - Inputs and Outputs  (0) 2020.10.06
1-4강 - String  (0) 2020.10.06
1-3강 - Java Arithmetic Operator  (0) 2020.10.06