一、类的定义
二、对象的创建
class Person{
id:number;
name:string;
age:number = 18;
constructor(id:number,name:string)
{
this.id = id;
this.name = name;
}
introduce():string{
return `hello,I am ${this.name},and I am ${this.age} years old.`
}
}
let person = new Person(1,'zhangsan');
console.log(person)
三、静态成员
声明静态成员 使用static关键字,静态成员隶属于类本身,而不属于某个对象实例
class Constants{
static count:number = 1;
}
class Utils{
static toLowerCase(str:string){
return str.toLowerCase();
}
}
console.log(Constants.count);
console.log(Utils.toLowerCase("Hello World"))
四、类的继承
继承是面向对象编程中的重要机制,允许一个类(子类或派生类)继承另一个(父类或基类)的属性和方法。子类可以直接使用父类的特性,并根据需要添加新的特性或覆盖现有的特性。
class Person{
id:number;
name:string;
age:number = 18;
constructor(id:number,name:string)
{
this.id = id;
this.name = name;
}
introduce():string{
return `hello,I am ${this.name},and I am ${this.age} years old.`
}
}
class Student extends Person{
classNumber:string;
constructor(id:number,name:string,classNumber:string)
{
super(id,name);
this.classNumber = classNumber;
}
introduceSTU():string{
return `hello,I am ${this.name},and I am ${this.age} years old.I am a student`
}
}
let student = new Student(1,'zhangsan','aaa');
console.log(student.introduceSTU());
4.1 访问修饰符
主要用于控制类成员的可访问性
五、接口
5.1 接口的定义
通常情况下接口只会包含属性和方法的声明,而不包含具体的实现细节,具体的细节由其实现类完成
interface Person{
id:number;
name:string;
age:number;
introduce():void;
}
5.2 接口的实现
interface Person{
id:number;
name:string;
age:number;
introduce():void;
}
class Stu implements Person{
id:number;
name:string;
age:number;
constructor(id:number,name:string,age:number){
this.id = id;
this.name = name;
this.age = age;
}
introduce():void{
console.log("Hello zzm")
}
}
let s1 = new Stu(1,'zzm',1);
console.log(s1.introduce())
六、多态
多态可以使同一类型的对象具有不同的行为
interface Person{
id:number;
name:string;
age:number;
introduce():void;
}
class Stu implements Person{
id:number;
name:string;
age:number;
constructor(id:number,name:string,age:number){
this.id = id;
this.name = name;
this.age = age;
}
introduce():void{
console.log("Hello stu")
}
}
class Tea implements Person{
id:number;
name:string;
age:number;
constructor(id:number,name:string,age:number){
this.id = id;
this.name = name;
this.age = age;
}
introduce():void{
console.log("Hello,tea")
}
}
let s1 = new Stu(1,'zzm',1);
let t1 = new Tea(1,"zzm",1);
s1.introduce();
t1.introduce();