객체지향(OOP), 절차지향(POP), class

svenskpotatis·2024년 8월 10일

객체(object)

  • instance of a class
  • 변수와 함수의 집합
  • 물리적으로 존재하거나 추상적으로 생각할 수 있는 것 중에서 자신의 속성을 가지고 있고, 다른 것과 식별 가능한 것

클래스(class)

  • 객체의 탬플릿, 설계도 (데이터의 구조(Field) + 데이터에 대해 수행할 수 있는 동작(Method))
  • 필드(Field)/속성(Attribute): 클래스 내에 저장되는 데이터 (state)
  • 생성자(Constructor): 객체가 생성될 때 호출되는 메소드로, 객체의 초기 상태 설정
  • 메소드(Method)/behavior: 객체가 수행할 수 있는 동작 정의 (behavior)

인스턴스(instance)

  • 클래스에 의해 생성된 객체 하나하나(대체로 객체와 인스턴스는 혼용해서 표현)

OOP, POP

  • OOP; Opject Oriented Programming, POP; Procedure Oriented Programming / Procedual Programming
  • POP

    • C
    • 컴퓨터가 작업하는 순서와 유사하여 컴퓨터의 연산처리 속도 빨라짐.
    • 클래스 기능 없음
  • OOP

    • Python, Java, C#, C++
    • 코드 간소화, 재사용 용이, 유지보수 편리
    • 실행속도 느림

코드 예시

Python

class Delphinidae: # 추상화: 일반적인 돌고래 클래스 정의
    def __init__(self, name, species, latest_sightseeing): # 생성자
        self.name = name
        self.species = species
        self.set_sightseeing(latest_sightseeing)  # set_sightseeing 메소드를 통해 초기화 - 유효성 검사

    def get_name(self):
        return f'이름: {self.name}'

    def set_sightseeing(self, latest_sightseeing):
        if latest_sightseeing < 0:
            raise ValueError('마이너스값 안됨')
        self.latest_sightseeing = latest_sightseeing

# 상속
class Orca(Delphinidae):
    def __init__(self, name, species, latest_sightseeing, ecotype):
        super().__init__(name, species, latest_sightseeing) # 상위 클래스의 생성자 호출
        self.ecotype = ecotype

orca1 = Orca('Snowflake', 'O. orca', 2023, 'North Atlantic')
print(orca1.species, orca1.get_name())  # 'O. orca 이름: Snowflake' 출력

Java

// 추상화
class Delphinidae { 
    public String name;
    public String species;
    public int latestSightseeing;
	
    public Delphinidae(String name, String species, int latestSightseeing) {
        this.name = name;
        this.species = species;
        this.setSightseeing(latestSightseeing);  // 데이터 유효성 검사
    }

    public String getName() {
        return "이름: " + this.name;
    }

    public void setSightseeing(int latestSightseeing) {
        if (latestSightseeing < 0) {
            throw new IllegalArgumentException("마이너스값 안됨");
        }
        this.latestSightseeing = latestSightseeing;
    }
}

class Orca extends Delphinidae { // 상속
    public String ecotype;

    public Orca(String name, String species, int latestSightseeing, String ecotype) {
        super(name, species, latestSightseeing); // 상위 클래스의 생성자 호출
        this.ecotype = ecotype;
    }
}

public class Main {
    public static void main(String[] args) {
        Orca orca1 = new Orca("Snowflake", "O. orca", 2023, "North Atlantic");
        System.out.println(orca1.species + " " + orca1.getName());  // 'O. orca 이름: Snowflake' 출력
    }
}

JavaScript

class Delphinidae {  // 추상화
    name = '';
    species = '';
    latest_sightseeing=0;
    constructor(name, species, latest_sightseeing) {
        this.name=name
        this.species=species
        this.setSightseeing(latest_sightseeing) // setSightseeing 함수 통해서 latest_sightseeing 생성
    }
    getName() {
        return '이름: ' + this.name;
    }
    setSightseeing(latest_sightseeing) {
        if(latest_sightseeing<0) {
            throw new Error('마이너스값 안됨')
        }
        this.latest_sightseeing=latest_sightseeing;
    }
} // 캡슐화

class Orca extends Delphinidae {   // 상속
    ecotype = '';
    constructor(name, species, latest_sightseeing, ecotype) {  // 생성자: 클래스의 속성값 초기화
        super(name, species, latest_sightseeing)        // 클래스의 속성값 가져오기
        this.ecotype=ecotype
    }
}

let orca1 = new Orca('Snowflake', 'O. orca', 2023, 'North Atlantic')   // 객체 만들기

console.log(orca1.species, orca1.getName());  // 'O. orca 이름: Snowflake' 출력

참고
OOP vs POP: Difference Between OOP and POP
프로그래밍 공통 : 절차지향(POP), 객체지향(OOP) 언어
개발자 면접 단골질문 객체지향 프로그래밍에 대해 알아보자
[JAVA] 객체와 클래스, 그리고 인스턴스의 차이
[ 파이썬 기초 — 2. 파이썬을 객체지향언어라 부르는 이유? #객체지향(OOP) #절차지향(POP) #Class ]
Coding Bootcamp: Creating classes
Java part-8 (Class and Object)
Understanding Object-Oriented Programming concepts


+ 범고래로 실습하고 싶어서 자료 찾아보다가 발견한 재밌는 사이트들(범고래 위키, https://orcaguardians.org) orcaguardians.org 는 맘에 드는 범고래를 입양(?)하면서 후원금을 낼 수 있다. 입양하면 그 범고래에 대한 자세한 정보를 알려주는 듯 한데 아이디어가 귀여우니까 나중에 해봐야겠다.

0개의 댓글