본문 바로가기

MATHrone/STUDY

TypeScript - 클래스, 접근제한자

 

class

 

member변수를 미리 선언해야함

class Car {
	name; //member변수를 미리 선언해두어야함 
    constructor(name :string){
    	this.name = name;
    }
    
    
    start(){
    	console.log("start");
    }
}

public / readonly를 사용해주면 member변수를 미리 선언하지 않아도 됨

 

 

Access modifier 접근 제한자

 

private / public / protected

접근 제한자 설명
public 자식 클래스나, 클래스 인스턴스에서 접근이 가능한 값(default)  
private (or #)  자식 클래스에서 접근 불가능함, 자신 내부에서만 사용할 수 있게됨 
protected 자식 클래스에서 접근이 가능함, 클래스 인스턴스에서는 참조가 불가능함   

 

//자기 자신 클래스
class Car {
	public name: string; //member변수를 미리 선언해두어야함 
    private color: string; // or #color :string(같은의미)
    protected year: number;
    
    
    constructor(name :string, color:string, year: number){
    	this.name = name;
        this.color = color;
        this.year = year;
    }
    
    
    start(){
    	console.log("start");
        console.log(this.name);
        console.log(this.color); // or this.#color
        console.log(this.year);
    }
}


//자식 클래스 
class Bmw extends Car {
    
    constructor(name :string, color:string, year: number){
    	super(name, color, year);
    }
    

    showName(){
        console.log(super.name);
    }
    
    showColor(){
        console.log(super.color); //error 
    }
    
    showYear(){
        console.log(super.year);
    }
}


//클래스 인스턴스
const mycar = new Bmw("black", "ccc", 1999);
console.log(mycar.name);
console.log(mycar.color); //error
console.log(mycar.year); // error
mycar.name = "zzz"; //변경가능 readonly가 들어가면 변경불가능 -> 이 경우 constructor로만 변경가능

 

 

static변수

 

static으로 선언된 정적 멤버변수는 this가 아닌 클래스명으로만 접근이 가능하다. 

class Car {
	name; //member변수를 미리 선언해두어야함
    static wheels = 4; 
    constructor(name :string){
    	this.name = name;
    }
    
    
    start(){
    	console.log("start");
        console.log(this.wheels);//error
        console.log(Car.wheels); //맞는 표현 
    }
}


const mycar = new Bmw("ccc");
console.log(Car.wheels);

 

 

 

추상 클래스 

 

abstract키워드를 사용해서 추상 클래스를 생성가능하며, new를 이용하여 객체를 생성할 수 없다.

extends를 통해서 자식클래스를 만들 수만 잇다. 

추상클래스 내 존재하는 추상 메소드는 상속받은 클래스(자식)에서 꼭 구현해야한다 (아니면 에러) 

모든 자식이 같은 메소드를 가지지만, 구체적인 내용은 자식마다 다를 수 있다. 

 

 

 

참고영상 

https://www.youtube.com/watch?v=17Oh028Jpis&list=PLZKTXPmaJk8KhKQ_BILr1JKCJbR0EGlx0&index=6 

 

728x90