多态&&public、private、protected、sta

2022-04-16  本文已影响0人  幸宇

// 多态
// 子类对父类的方法进行了重写,子类和父类调同一个方法时会不一样。

// class Person{
//     name:string
//     constructor(name:string){
//         this.name = name
//     }
//     speak(){
//         console.log(`${this.name} is speaking`)
//     }
// }
// // const p1 = new Person('zx')
// // p1.speak()

// class Student extends Person{
//     speak(){
//         return `Student ${super.speak()}`
//     }
// }

// const s1 = new Student('zhangxing')
// console.log(s1.speak())

// public
// public,公有的,一个类里默认所有的方法和属性都是 public。
// class Person{
//     public name:string
//     public constructor(name:string){
//         this.name = name
//     }
//     public speak(){
//         console.log(`${this.name} is speaking`)
//     }
// }
// public 可写可不写,不写默认也是 public。
// private
// private,私有的,只属于这个类自己,它的实例和继承它的子类都访问不到。
// class Person{
//     private name:string
//     private constructor(name:string){
//         this.name = name
//     }
//     private speak(){
//         console.log(`${this.name} is speaking`)
//     }
// }
// 实例访问 name 属性,会报错:
// const p1 = new Person('zhangixng')
// p1.name
// 继承它的子类 访问 name 属性,会报错:
// class Student extends Person{
//     study(){
//         console.log(`${this.name} need study`)
//     }
// }

// protected
// protected 受保护的,继承它的子类可以访问,实例不能访问。
class Person{
    protected name:string
    protected constructor(name:string){
        this.name = name
    }
    public speak(){
        console.log(`${this.name} is speaking`)
    }
}
// 实列不可以访问
// const p1 = new Person('zx')
// 子类可以访问
class Student extends Person{
    study(){
        console.log(`${this.name} needs study`)
    }
}

// static
// static 是静态属性,可以理解为是类上的一些常量,实例不能访问
// 比如一个 Circle 类,圆周率是 3.14,可以直接定义一个静态属性。

class Circle{
    static pi = 3.14
    public radius:number
    public constructor(radius:number){
        this.radius = radius
    }
    public calcLength(){
        //  // 计算周长,直接访问 Circle.pi
        return Circle.pi*this.radius*2
    }
}
// 实列访问,会报错
const c1 = new Circle(10)
上一篇 下一篇

猜你喜欢

热点阅读