//面向对象
//属性修饰符 public private protected readonly
class Person {
public name: string;
private age: number;
// #age: number;
protected sex: string;
constructor(name: string, age: number, sex: string) {
this.name = name;
this.age = age;
this.sex = sex;
}
sayHello() {
console.log('hello', this.sex);
}
}
const p1 = new Person('小明', 18, '男');
console.log('p1', p1);
// console.log('age',p1.age);
// console.log('sex',p1.sex);
p1.sayHello();
class Student extends Person {
private readonly age: number;
constructor(name: string, age: number, sex: string) {
super(name, age, sex);
this.age = age;
}
// this.age不允许访问
say() {
console.log('say', this.sex, this.age);
// this.age = 2;不允许修改
}
private say2() {
console.log('say2');
}
}
const s1 = new Student('小红', 18, '女');
s1.say();
// s1.say2()
//抽象类
abstract class Animal {
abstract eat(): void;
run() {
console.log('run');
}
}
class Dog extends Animal {
eat() {
console.log('吃狗粮');
}
}
const dog = new Dog();
dog.eat();
dog.run();
//接口
interface Human {
name: string;
eat: () => void;
}
class Man implements Human {
name: string;
constructor(name: string) {
this.name = name;
}
eat() {
console.log(`${this.name}吃东西`);
}
}
const man = new Man('小明');
man.eat();