classGreeter{// 새로운 클래스 선언
greeting:string;constructor(message:string){this.greeting = message;// 클래스 맴버 참조}greet(){return"Hello, "+this.greeting;}}
console.log(newGreeter("world").greet());// 클래스의 인스턴스 생성, 객체를 생성, 초기화
Inheritance
상속받아 기존 클래스를 확장하여 새로운 클래스를 생성할 수 있다.
classAnimal{
name:string;constructor(theName:string){this.name = theName;}move(distanceInMeters:number=0){
console.log(`${this.name} moved ${distanceInMeters}m.`);}}classHorseextendsAnimal{constructor(name:string){super(name);}move(distanceInMeters =45){
console.log("Galloping...");super.move(distanceInMeters);}}let tom: Animal =newHorse("Tommy the Palomino");
tom.move(34);// output// Galloping...// Tommy the Palomino moved 34m.
extends 키워드를 사용하여 상속받는다. 상속받은 클래스는 기본 클래스에서 super()를 호출해야 한다.(상속받은 클래스에서 생성자 함수를 사용하는 경우에)
public, private and protected
public
기본은 public이다. 위의 Animal 클래스의 경우 특별히 쓰여져 있지 않았지만, public으로 인식된다.
abstractclassDepartment{constructor(public name:string){}printName():void{
console.log("Department name: "+this.name);}abstractprintMeeting():void;}classAccountingDepartmentextendsDepartment{constructor(){super("Accounting and Auditing");}printMetting():void{
console.log("The Accouting Department meets each Monday at 10am.");}
댓글
댓글 쓰기