짱짱해커가 되고 싶은 나

Ch4. Objects and Classes (1) 본문

programming/java

Ch4. Objects and Classes (1)

동로시 2019. 10. 9. 00:30

4.1 Introduction to OOP

Structured(procedural) programming (set of collaborating procedures)

: Program = Algorithms + Data structures

1. algorithm 설계

2. 데이터 저장 방법 찾기

∴ 데이터를 조작하는 procedures를 먼저 결정하고 데이터 조작을 쉽게 할 수 있는 구조를 결정.

-> procedures는 structured programming에서 shared data위에서 동작한다.

OOP(object-oriented programming) (set of collaborating objects)

-> 데이터를 먼저 집어 넣고 이에 맞는 알고리즘을 찾는다.

- 종종 understand, correct, modify가 더 쉽다.

software object - physical/conceptual 개체를 나타냄.

: 두 부분으로 구성된 독립형 소프트웨어 구조(self-contained software structure)

 

object = data(attributes(속성)) + methods(behaviors)

Class : 클래스 내의 object의 common behavior 정의

OO program = class들의 집합

Encapsulation(information hiding) : 구현 세부사항을 숨겨 같은 클래스 내의 함수만이 객체의 데이터에 접근 가능

ex) 2,000개의 접근 가능한 global data가 있을 때 버그를 찾는 경우

OOP : 100개의 class, 각 클래스는 20개의 method. -> 20개의 method만 검사하면 됨.

procedural programming : 2,000개를 접근해야함

 

모든 코드들은 클래스 내에 존재해야 한다.

클래스 ~ 객체가 만들어지는 template/blueprint

"new" operator를 사용하여 클래스로부터 object를 생성하고 class의 constructor를 생성.

Constructor의 이름은 클래스 이름과 같으며, new operator를 호출할 때 실행되며 return value가 없다.

class는 한 패키지안의 data와 behavior를 encapsulate하고 객체의 user로부터 상세한 내용을 숨긴다.

instance fields = 한 객체의 bits of data

method = data의 작동 절차

spectific object : class의 instance = have sepcific values of its instance fields

객체에서 함수를 invoke(호출)할 때마다 state는 바뀔 것이다.

한 클래스의 한 객체는 클래스 내의 공유되된 method와 state(instance variables)와 identity를 갖는다.

 

Encapsualtion 때문에, 한 클래스의 메소드는 다른 클래스의 instance field에 직접 access 불가능.

-> 프로그램은 method call을 통해서만 object data에 접근할 수 있음.

Encapsulatoin 때문에, 한 객체는 "black box" reliability.

-> 한 클래스(server) 내에서 데이터 저장 방식을 바꾸더라도 다른 클래스(client)는 어떤 변화가 있는지 알 수 없다. 왜냐면 server class의 public 함수를 호출함으로써 server의 data에 접근할 수 있기 때문이다.

 

3 characteristic of object

1. behavior : object에 어떤 함수들을 적용할 수 있는가.

- 같은 클래스의 인스터인 모든 객체는 동일한 method(behavior) 공유

2. state : method를 호출할 때 object는 어떻게 반응하는가.

- 시간에 따라 변경 가능, state의 변화는 함수 호출로의 결과.

3. identity : 같은 behavior과 state를 지닌 object들과 어떻게 구별되는가.

- state는 behavior를 변경 할 수 있다.

- behavior는 state를 변경 할 수 있다.

 

Relationships between classes

a) use-a (Dependence) : class A는 class B의 객체를 사용/조작 = class A depend on class B

b) has-a (Aggregation) : class A는 class B의 instance field.

c) is-a (Inheritance) : class B는 class A의 child class.

4.2 Using Predefined Classes

ex) java.lang.Math - Math.sqrt(x)

객체를 생성하거나 instance field를 초기화하지 않아도 됨.

함수의 이름, 파라미터만 알면 사용 가능. sqrt함수가 어떻게 구동하는지 알 필요 없음

-> Math class는 함수들만 encapsulates. 왜냐면 data는 없기 때문에 data는 아님.

 

To work with objects:

1) construct & initial stae (constructor)

2) apply methods

 

constructor : 클래스의 new instance 생성&초기화하는 특별한 함수.

ex1) Data birthday = new Data(); //birthday : object value

ex2) String s = birthday.toString();

 

ex) Data deadline; //deadline는 heap 영역의 실제 object refer X

     String s = deadline.toString(); //error : deadline = null

          null일 경우 : runtime error

          uninitialized : compie-time error

    ∴ null이거나 uninitialized variable은 함수 호출에 사용하지 말 것.

-> Data deadline = new Data();

-> Data deadline;

    deadline = new Data();

 

object variabel : 실제 object를 포함하는 것이 아니라 그것을 refer(참조) 하는 것이다.

 

ex) java.time.LocalDate (year-month-day) //java.time pacakge : 날짜,시간,인스턴스,기간에 대한 기본 API

LocalDate rightNow = LocalDate.now();

LocalDate newYearsEve = LocalDate.of(1999,12,31);

LocalDate aThousandDaysLater = newYearsEve.plusDays(1000); //newYearsEve 객체를 수정하지 않고 새로운 객체 생성

year = aThousandDaysLater.getYear();

 

Accessor method : object state를 modify(수정) 하지 않는다.

ex) 모든 LocalDate method는 accessor method.

Mutator mthod : object state 수정

ex) GregorianCalendar someDay = new GregorianCalnedar(1999,11,31);

     someDay.add(Calendar.DAY_OF_MONTH,1000);

 

4.3 Defining Your Own Classes

Implicit parameter(this)

Explicit parameter

 

Benefits of Encapsulation

1. accessor method와 mutator method를 제외한 모든 method code를 변경하지 않고 내부 표현 변경 가능.

2. mutator method는 error checking 가능.

※ accessor method가 mutable object를 참조값을 반환하지 않도록 주의.

 

같은 class 내의 private data에 접근 가능. 

fianl instance : 변하지 않음, 무조건 initialized(at the declaration, at constructor, at the object initialization block)

- immutable class에 좋음.

- 어떤 method도 object를 변경할 수 없는 class는 변경할 수 없다. ex)String

- mutable class에서 final keyword는 변경할 수 없음을 강조하지만, heap에서는 변경할 수 있다.

 

4.4

Static field : class field라고 불리며, class마다 한 개 씩 존재.

static final field : shared constanct

static method : no implicit(this) paremter, only access static field, can't call non-static method, 객체 없이 호출 가능

non-static method : can access static field&method.

 

Note 1: The main() method does not operate on any objects.

Note 2: when a program starts, there is no any objects yet.

Note 3: The static main() executes, and constructs the objects that the program needs.

 

4.5 Method Parameter

call by value : value를 받음, 수정 가능하지만 실제 값으로 전달되지는 않음.

call by reference : location을 받음.

 

java는 call by value만 사용하기 때문에 method가 모든 parameter value의 사본을 가져옴.

-> method는 전달 된 매개 변수의 내용을 수정할 수 없음.

※ 모든 것이 call by value로 이용됨. (primitives, object 등)

 

methods can't modify numeric parameters.

methods can change the sate of object parameters.

methods can't attack new objects to object parameters.

Comments