鸿蒙初开,开天辟地
权限修饰符实际开发中的应用
访问的权限修饰符,在面向对象编程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方法我们可以直接使用






2521

被折叠的 条评论
为什么被折叠?



