Elice SW engineer - TIL day 24 - 2

Circlewee·2022년 5월 6일
0

Elice SW 2 TIL

목록 보기
22/31

2. Class

  • 객체지향 프로그래밍(OOP)를 할 때 주로 사용됌
  • 프로그램의 유연하며 변경이 용이해지고 개발과 보수를 간편하게 만든다. 직관적인 코드 분석이 가능하다.
  • 코드의 강한 응집력, 약한 결합력이 특징
  • field, constructor, method로 이루어져 있고 이를 통틀어 member라 부른다.
  • 인스턴스(instance): new 연산자에 의해 생성된 객체
class Person {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
  // say() 같은 경우에는 반환값이 string을 유추할 수 있으므로 명시하지 않아도 된다.
  say() {
    return `Hello, My name is ${this.name}`;
  }
}
const p1 = new Person('park'); // instance

2.1 접근 제어자 / 상속

2.1.1 접근 제어자

  • 속성 또는 메소드로의 접근을 제한하기 위해 사용한다.
  • public > protected > private (package 개념이 존재하지 않기 때문에 default는 존재하지 않음)
class Animal {
  public name: string;
  constructor(name: string) {
    this.name = name;
  }
}
new Animal('cat').name;
class Animal {
  private name: string;
  constructor(name: string) {
    this.name = name;
  }
  getName() {
    return this.name;
  }
}
new Animal('cat').name; // error: name이 private로 선언되었기 때문에 Animal클래스에서만 접근 가능
new Animal('dog').getName();

2.1.2 상속

  • 존재하는 클래스를 확장해 새로운 클래스를 생성할 수 있음.
  • 파생된 클래스는 하위클래스(subclass), 기초 클래스는 상위클래스(superclass)라고 부른다.
  • 만약 부모클래스에 생성자가 있다면 자식클래스는 super()를 이용해서 반드시 호출해줘야 한다.
// superclass
class Animal {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
  move(distance: number) {
    console.log(`Animal moved ${distance}m.`);
  }
}
// subclass
class Dog extends Animal {
  constructor(name: string) {
    super(name);
  }
  makeSound() {
    console.log('bark!');
  }
}
class Cat extends Animal {
  constructor(name: string) {
    super(name);
  }
  makeSound() {
    console.log('meow!');
  }
}

const dog = new Dog('dog');
dog.move(10);
dog.makeSound(); // bark!
const cat = new Cat('cat');
cat.move(5);
cat.makeSound(); // meow!

2.2 getter & setter / readonly / static

2.2.1 getter & setter

  • 비공개로 설정하려는 속성을 private로 설정하고 읽고 수정하는 getter, setter 함수를 구현하는 것
class Person {
  // 네이밍 컨벤션
  private _name: string;
  
  get name() {
    return this._name;
  }
  set name(name: string) {
    this._name = name;
  }
}

let person = new Person();
console.log(person.name); // 자동으로 getter함수를 이용해 값을 가져온다. person._name이아님
person.name = 'son'; // 이 부분도 setter함수를 이용해 값을 설정한다.

2.2.2 readonly

  • 읽기만 가능한 속성을 선언할 때 사용
  • readonly로 설정된 값은 선언할 때나 생성자에서 초기화할 때 아니면 수정이 불가능하다.
class Person {
  readonly age: number = 20; // 선언 초기화
  constructor(age: number) {
  	this.age = age;
  }
}

let person = new Person(10); // 생성자 초기화
person.age = 20; // error

2.2.3 static

  • 전역 멤버를 선언할 때 사용, 전역멤버란 객체마다 할당되지 않고 클래스의 모든 객체가 공유하는 멤버를 말한다.
class Grid {
  static origin = { x:0, y:0 }
  
  calculateDistance(): void {
    console.log(Grid.origin.x * Grid.origin.y);
  }
}

const grid = new Grid();
Grid.origin = { x:3, y:3 } // Grid class 자체를 사용
grid.calculateDistance(); // grid instance 사용

2.3 추상 클래스(abstract class)

  • 다른 클래스들이 파생될 수 있는 기초 클래스, 직접 인스턴스화 할 수 없다.
abstract class Animal {
  protected name: string;
  
  constructor(name: string) {
  	this.name = name;
  }
  
  abstract makeSound(): void
  
  move(): void {
  	console.log('move!');
  }
}

class Dog extends Animal {
  constructor(name: string) {
  	super(name); // 반드사 super()를 통해 부모의 생성자를 호출
  }
  // 반드시 구현해야함
  makeSound(): void {
  	console.log(`${this.name} 멍멍!`);
  }
}

const animal = new Animal('animal') // error: abstract class는 인스턴스화 할 수 없음
const dog = new Dog('진돗개');
dog.makeSound();
profile
공부할 게 너무 많아요

0개의 댓글

관련 채용 정보