class Car {
color: string;
constructor(color: string) {
this.color = color;
}
start() {}
}
const bmw = new Car('red');
- 여기서 class 내 속성 중에 변수를 먼저 선언하기 싫다면 constructor 내에 매개변수 앞에 readonly나 public을 이용하면 된다.
- 접근 제한자(Access modifier) - public, private, protected 이용하면 된다.
// 접근 제한자(Access modifier) - public, private, protected
class Car {
name: string = 'car';
color: string;
constructor(color: string) {
this.color = color;
}
start() {
console.log('start');
}
}
class Bmw extends Car {
constructor(color: string) {
super(color);
}
showName() {
console.log(super.name);
}
}
const z4 = new Bmw('black');
- error가 발생하지 않는다. class Car에서 name을 private를 걸어준다면
// 접근 제한자(Access modifier) - public, private, protected
class Car {
private name: string = 'car'; //#name으로 사용해도 된다. 밑에서도 #을 모두 붙여준다.
color: string;
constructor(color: string) {
this.color = color;
}
start() {
console.log('start');
}
}
class Bmw extends Car {
constructor(color: string) {
super(color);
}
showName() {
console.log(super.name);
}
}
const z4 = new Bmw('black');
- 부모 class에서 private하게 사용하고 있으므로 showName에서 error가 발생한다.
// 접근 제한자(Access modifier) - public, private, protected
class Car {
readonly name: string = 'car';
color: string;
static wheels = 4;
constructor(color: string) {
this.color = color;
}
start() {
console.log('start');
}
}
class Bmw extends Car {
constructor(color: string) {
super(color);
}
showName() {
console.log(super.name);
console.log(Car.wheels);
}
}
const z4 = new Bmw('black');
console.log(Car.wheels);
- 마찬가지로 protected에서도 사용 가능하다.
- protected와 public의 차이는 무엇인가?
- 자식 class에서는 protected는 참조할 수 있지만 class intance에서는 참조가 불가하다.
- public ==> 자식 클래스, 클래스 인스턴스 모두 접근 가능
- protected ==> 자식 클래스에서만 접근 가능
- private ==> 해당 클래스 내부에서만 접근 가능
- static ==> 해당 클래스의 요소에 접근할 때 클래스 명을 사용해서 접근할 수 있다.
// 추상 class
abstract class Car {
color: string;
constructor(color: string) {
this.color = color;
}
start() {
console.log('start');
}
}
// const car = new Car('red');
class Bmw extends Car {
constructor(color: string) {
super(color);
}
}
const z4 = new Bmw('black');
- 추상 클래스는 오직 상속을 통해서만 클래스를 만들 수 있다.
// 추상 class
abstract class Car {
color: string;
constructor(color: string) {
this.color = color;
}
start() {
console.log('start');
}
abstract doSomething(): void;
}
// const car = new Car('red');
class Bmw extends Car {
constructor(color: string) {
super(color);
}
doSomething() {
alert(3);
}
}
const z4 = new Bmw('black');
- 추상화는 property나 이름만 선언해주고 구체적인 기능 상속받는 곳에서 작성해주는 것을 의미한다.