본문 바로가기

Front-End/TypeScript

TypeScript #12 (OOP 예제 #1~5)

반응형

✅ 문제 1. 간단한 클래스 만들기

- Dog라는 클래스를 만들어서 "멍멍!"이라고 출력하는 bark() 메서드를 만들어보기

멍멍!
class Dog {			// Dog라는 클래스 생성
    bark() {			// bark 메서드 생성
        console.log("멍멍");
    }
}

let dog = new Dog();	// Dog 클래스를 사용하는 dog 객체 생성
dog.bark();		// dog 객체에게 bark 메서드를 호출시키기

 

 

 

✅ 문제 2. 생성자 연습

- User 클래스를 만들어 생성자에서 name을 받고, greet() 메서드에서 "안녕하세요, 제 이름은 홍길동입니다."와 같이 출력되도록 하기.

안녕하세요, 제 이름은 홍길동입니다.
class User {            		// User 라는 클래스 생성

    name: string;

    constructor(name: string) {         // 생성자 생성 (초기화 담당)
        this.name = name;               // name 이라는 변수를 생성자에서 쓰겠다고 지정 (this)
    }

    // constructor(public name: string) {}          // 요즘 쓰는 방식

    greeting() {
        console.log(`안녕하세요, 제 이름은 ${this.name}입니다.`)		// 메서드에서도 마찬가지
    }
}


let user = new User("홍길동");		// "홍길동"이라는 name을 가진 user 객체 생성

user.greeting();			// user 객체에게 greeting 메서드 호출시키기

 

 

 

✅ 문제 3. 속성 변경하기

- Counter 클래스를 만들고 count라는 숫자 속성을 가지며, increase() 메서드를 호출할 때마다 1씩 증가하게 만들기.

- show() 메서드로 현재 숫자를 출력.

현재 값: 1
현재 값: 2
class Counter {         // Counter 클래스 생성
    count: number = 0;      // count를 0으로 변수 지정

    increase () {           // ++ : 호출할 때마다 1씩 증가하는 메소드 
        this.count++;       // 클래스에서 지정한 count 변수를 쓰기 위해 this 사용 
    }

    show () {               // count 변수의 값을 확인하기 위한 메소드
        console.log(this.count);
    }

}


let counter = new Counter();        // Counter 클래스의 인스턴스(객체) 생성

// counter 객체에서 증가하는 메소드를 호출
counter.increase();
counter.increase();
counter.increase();

// count 변수의 값을 확인하는 메소드를 호출
counter.show();

 

 

 

✅ 문제 4. 클래스 간 관계 만들기

- Car 클래스와 Driver 클래스를 만들고, Driver가 Car를 운전한다는 구조로 drive() 메서드를 구현하기.

- "홍길동이 자동차를 운전합니다." 라고 출력.

class Car {        // Car 클래스 생성

    drive(driver: Driver) {     				// driver 변수는 Driver 클래스로부터 받음
        console.log(`${driver.name}님, 운전을 시작합니다.`);    // driver 변수에서 name 호출
    }
    
}

class Driver {      // Driver 클래스 생성
    name: String;   // 운전자의 name 을 받음
}


let car = new Car();        // Car 클래스의 객체 생성
let driver = new Driver();  // Driver 클래스의 객체 생성
driver.name = "홍길동";     // driver 변수에서 name을 호출해서 "홍길동" 이라는 값을 넣음

car.drive(driver);      // car 객체에서 drive 메서드를 호출. 이때 driver 변수를 넣음

 

 

 

✅ 문제 5. 배열과 객체

- Book 클래스를 만들고 title, author 속성을 가지게 한 뒤, 여러 개의 책 객체를 배열에 넣고, 모든 책 정보를 출력하기

책 제목: TypeScript 기본, 저자: 이지스
책 제목: 모던 자바스크립트, 저자: 김코딩
class Book {            // Book 클래스 생성
    title: string;      // title과 author를 받을 속성으로 지정
    author: string;
}

// 객체 생성, 각 객체들의 속성 설정
let book = new Book();
book.title = "책1";
book.author = "저자1"
let book2 = new Book();
book2.title = "책2";
book2.author = "저자2"
let book3 = new Book();
book3.title = "책3";
book3.author = "저자3"


// 배열을 만들어서 배열 안에 저장
let books = [book, book2, book3];
let books2 = Array<Book>();

books2.push(book);
books2.push(book2);
books2.push(book3);


// 반복문 : 배열 안에 있는 각 객체들이 가진 속성 호출
for (let i = 0; i < books.length; i++) {
    console.log(`책 이름: ${books[i].title}, 저자: ${books[i].author}`);
}

 

 

 

 

 

연습 포인트 요약

 

 

 

 

 

 

반응형

'Front-End > TypeScript' 카테고리의 다른 글

TypeScript #14 (제네릭)  (0) 2025.07.04
TypeScript #13 (OOP 연습 문제 #1~10)  (0) 2025.07.03
TypeScript #11 (객체 지향)  (0) 2025.07.03
TypeScript #10 (함수 유효성 검사)  (0) 2025.07.02
TypeScript #9 (함수)  (0) 2025.07.02