/*~migrated from old blog ~*/
Class 객체지향 프로그래밍의 Class
이번 챕터에서 얻어가는 5가지 개념들
- public : 밖에서도 접근할 수 있다.
- private : 밖에서 절대로 접근할 수 없다.
- protected : 상속 받은 class에서는 접근할 수 있다.
- abstract class
- abstract method
- public과 private
class Player {
constructor(
private firstName : string,
private lastName : string,
private age : number,
public url : string
)
{}
}
const me = new Player('me', 'me', 32, '/blogs')
console.log(me.firstName)
// 컴파일 에러
// Property 'firstName' is private and only accessible within class 'Player'.
console.log(me.url)
// '/blogs' 출력 . public이기 때문에 class 밖에서도 접근 가능하다.
추상 클래스 Abstract Class
그 자체로는 인스턴스를 생성할 수 없고 상속을 줄 수만 있는 클래스
오직 다른 클래스들이 상속받아 인스턴스를 생성할 수 있다.
쉽게 생각해서 ⇒ 클래스의 타입을 요약abstract해둔 것으로 생각할 수 있다.
abstract class User {
constructor(
private firstName : string,
private lastName : string,
private age : number,
public url : string
)
{}
}
class Player extends User{
}
// 컴파일 에러 : 추상 클래스로 객체 생성 X
// const me = new User('me', 'me', 32, '/blogs')
// Cannot create an instance of an abstract class.(2511)
const me = new Player('me', 'me', 32, '/blogs')
추상 메소드 상속 abstract method
추상 클래스에서 메소드를 그대로 상속할 수 있다.
또한 추상 클래스 내부에 추상 메소드를 정의할 수 있다.
추상 메소드에선 매개변수, 반환값의 타입만 지정해준 뒤, 그 후 상속 받는 클래스에서 구체적 그 함수를 정의할 수 있다.
abstract class User { constructor(
protected firstName : string,
protected lastName : string,
private age : number, // age에는 접근할 수 없다.
public url : string ) {}
abstract getFullName():string
//추상 메소드 getFullName은 문자열을 반환한다.
}
class Player extends User{
getFullName() {
return `${this.firstName} ${this.lastName}`
}
}
class PlayerTwo extends User {
getFullName() {
return `${this.firstName} is first name`
}
}
const my = new PlayerTwo ( 'mye', 'lastMew' ,32, 'ao')
const me = new Player('me', 'mewo', 32, '/blogs')
console.log(me.getFullName())
// 'me mewo' 출력
console.log(my.getFullName())
// 'mye is first name' 출력
같은 메소드도 다른 자식 클래스에서 다르게 정의했기 때문에 다른 결과가 나온다.
protected
상속 받은 클래스에서 인스턴스의 키에 접근하고자 할 때, private 대신 protected를 적용하면 자식 클래스 안에서는 접근할 수 있게 된다.
(자식 클래스 외부는 X)
abstract class User {
constructor(
protected firstName : string,
protected lastName : string,
//추상 메소드 getFullName은 문자열을 반환한다.
}
class Player extends User{
}
const me = new Player('me', 'me', 32, '/blogs')
console.log(me.lastName)
// 컴파일 에러
// Property 'lastName' is protected and
// only accessible within class 'User' and its subclasses.(2445)