鸿蒙Harmony OS Next原生开发TS的权限修饰符实际开发应用

鸿蒙初开,开天辟地

权限修饰符实际开发中的应用

访问的权限修饰符,在面向对象编程OOP中是非常重要的概念,我们要控制类的成员属性方法的可见性可访问性,需要使用该属性和方法的地方应当让它可见

class Java{
  private id:number;
  protected version:string;
  public static print(){
    console.log("哈哈哈哈哈哈哈哈哈");
  }
  public name:string;
  constructor(id:number,version:string,name:string){
    this.id = id;
    this.version = version;
    this.name = name;
  }
  helloWorld(){
    console.log(this.version,this.name);
  }
}
class Spring extends Java{
  java:string;
  constructor(id:number,version:string,name:string,java:string){
    super(id,version,name);
    this.java = java;
  }
  javaWorld(){
    console.log(this.java);
  }
}
let java:Spring = new Spring(1,"1.8","javac","springBoot");
java.helloWorld();
Spring.print();

这里我们声明了private,protected和public

被标记为private的属性就只能在该类中使用了,因此我们需要使用它,子类就必须要用super的形式,去指向这个属性,或者直接使用父类对象

因为实际指向了子类对象,因此父类的属性就访问不了 

使用权限修饰符

protected的属性或方法就是父子类都可以使用的,但是非父子类的对象就无法访问了 

class Java{
  private id:number;
  protected version:string;
  public name:string;
  public static print(){
    console.log("哈哈哈哈哈哈哈哈哈");
  }

  constructor(id:number,version:string,name:string){
    this.id = id;
    this.version = version;
    this.name = name;
  }
  helloWorld(){
    console.log(this.version,this.name);
  }
}
class Spring extends Java{
  java:string;
  constructor(id:number,version:string,name:string,java:string){
    super(id,version,name);
    this.java = java;
  }
  javaWorld(){
    console.log(this.java);
  }
}
let java:Java = new Spring(1,"1.8","javac","springBoot");
java.helloWorld();
console.log(java.name);
Spring.print();

protected修饰符

public就非常好理解,任何位置和调用都可以访问到这个属性或者方法,实例的方法需要一个实例

而工具类或是常量就可以直接获取到,public我们用的也是最多的

public的print方法我们可以直接使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值