코드스테이츠(TIL 2일)

유승현·2021년 6월 8일

OOP 객체 지향언어

oop 객체지향언어 개념은 어느정도 이해했지만 class개념을 코드로 표현하는게 아직 미숙하고 안친한것같아서 오늘은 코드와 친해질려고 노력을 했습니다.

일단 oop는 말그대로 객체와 관련된 개념입니다 이 개념의 중요한 목적어?들이 클래스와 인스턴스인데 클래스는 객체를 만들기 위한 생성자(constructor)함수를 사용해야 합니다.

constructor 란 클래스는 하나의 constructor를 가질 수 있습니다.. constructor는 new ()명령을 통해 실행되어 인스턴스를 초기화하는 역할을 하며, name처럼 매개변수를 둘소있다고도 합니다.

class Animal {
  constructor(name) {
  }
}

export default Animal // Animal을 다른데서도 쓸수 있어~ 하는 느낌입니다.

클래스의 프로퍼티 값은 constructor안에 선언합니다. this.name

class Animal {
  constructor(name) {
    this.name = name;
  }
}
//근데 여기서 만약에 다른js파일에서 Animal을 불러다가 새로운 값을 바꾸면
import Animal from './Animal'

let anim = new Animal('jake') // anim인스턴스의 프로퍼티 name의 값은 'jake'가 됨.

이처럼 클래스의 몇가지 개념들이 있습니다.
상속 은 말그대로 해당 클래스의 모든내용을 다른 클래스에 그대로 복사한다는 의미이며 Animal 클래스의 프로퍼티 this.name과 메소드 getName()을 다른 클래스에 그대로 상속할수 있습니다.

class Animal {
    constructor(name) {
        this.name = name;
    }
    
    getName() {
        return this.name;
    }
}

export default Animal;

------------------------

import Animal from './Animal';

class Dog extends Animal {
    constructor(name) {
        super(name);
    }
}

export default Dog;

extends 키워드를 사용해 Dog 클래스가 Animal 클래스를 상속했고, 이제 Animal 클래스는 Dog 클래스의 superclass가 되었고, Dog 클래스는 Animal 클래스의 subclass가 되었습니다. Dog 클래스는 Animal 클래스가 가지고 있는 this.name과 getName()을 똑같이 갖습니다.

subclass의 constructor에는 super()를 넣어 superclass의 constructor를 호출할 수도 있으며 subclass에서 super()를 사용하지 않아도 되는 경우 에러가 발생하지는 않지만, 그래도 super()를 명시하길 권장한다고 합니다.

클래스를 상속할 때는 IS-A 관계나 HAS-A 관계를 만족하는지 확인해야 합니다. "사과는 과일이다(Apple is a fruit)"는 IS-A 관계를 만족하므로 Fruit 클래스가 Apple 클래스의 superclass가 될 수 있고 "차에는 바퀴가 있다(Car has a wheel)"는 HAS-A 관계를 만족하므로 Car 클래스가 Wheel 클래스의 superclass가 될 수 있습니다. 또 한가지 중요한 개념은 오버라이딩 = subclass가 superclass의 메소드를 덮어쓰는것을 의미합니다.

profile
멋진 사람이 되고 싶습니다.

0개의 댓글