Web Devlopment/TypeScript
#5 클래스 (class)
키모형
2025. 3. 26. 21:31
반응형
// Class
class Car {
color: string;
constructor(color: string){
this.color=color;
}
start(){
console.log("start");
}
}
const bmw = new Car("red");
접근 제한자 : public, private , protected
다른 언어와 동일.
public : 부모클래스 내부, 자식클래스 내부, 외부 객체에서 모두 접근가능
private : 부모클래스 내부에서만 접근가능
protected : 보모클래스, 자식클래스 내부까지만 접근가능
// Class
class Car {
private 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(this.name); // private 일때 자식 클래스에서 사용못함
}
}
const z4 = new Bmw("black");
z4.showName();
// console.log(z4.name); // public에서만 접근가능
readlony : 읽기전용, 수정불가.
class Car {
readonly 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(this.name);
}
}
const z4 = new Bmw("black");
z4.showName();
console.log(z4.name);
z4.name="my-car"; // readonly 속성으로 변경불가
static
// Class
class Car {
readonly name: string = "car";
color: string;
static wheels: number = 4;
constructor(color: string){
this.color=color;
}
start() {
console.log("start");
console.log(Car.wheels); // static 맴버변수
}
}
class Bmw extends Car {
constructor(color:string) {
super(color);
}
showName() {
console.log(this.name);
console.log(Bmw.wheels); // static 맴버변수
}
}
const z4 = new Bmw("black");
z4.showName();
console.log(z4.name);
// z4.name="my-car"; // readonly 속성으로 변경불가
console.log(Bmw.wheels); // static 맴버변수
추상 class, 추상 method
// 추상 Class
abstract class Car {
readonly name: string = "car";
color: string;
static wheels: number = 4;
constructor(color: string){
this.color=color;
}
start() {
console.log("start");
console.log(Car.wheels); // static 맴버변수
}
abstract doSomething():void;
}
// 추상 클래스는 new로 생성안되며 상속클래스를 생성해서 사용해야함
// Cannot create an instance of an abstract class.
// const car = new Car("red");
class Bmw extends Car {
constructor(color:string) {
super(color);
}
showName() {
console.log(this.name);
console.log(Bmw.wheels);
}
doSomething(){
console.log('doSomething');
}
}
const z4 = new Bmw("black");
z4.showName();
z4.doSomething();
반응형