public
修饰符:
- 在父类中使用
public
修饰的属性或方法,子类可以自由访问。
- 示例代码:
class Parent {
public publicProperty: string;
public publicMethod() {
return 'This is a public method';
}
constructor() {
this.publicProperty = 'Public property value';
}
}
class Child extends Parent {
accessPublic() {
return this.publicProperty + ','+ this.publicMethod();
}
}
const child = new Child();
console.log(child.accessPublic());
private
修饰符:
- 在父类中使用
private
修饰的属性或方法,子类无法直接访问。
- 示例代码:
class Parent {
private privateProperty: string;
private privateMethod() {
return 'This is a private method';
}
constructor() {
this.privateProperty = 'Private property value';
}
}
class Child extends Parent {
// 以下代码会报错,因为无法访问父类的私有成员
// accessPrivate() {
// return this.privateProperty + ','+ this.privateMethod();
// }
}
protected
修饰符:
- 在父类中使用
protected
修饰的属性或方法,子类可以访问,但不能在类外部直接访问。
- 示例代码:
class Parent {
protected protectedProperty: string;
protected protectedMethod() {
return 'This is a protected method';
}
constructor() {
this.protectedProperty = 'Protected property value';
}
}
class Child extends Parent {
accessProtected() {
return this.protectedProperty + ','+ this.protectedMethod();
}
}
const child = new Child();
console.log(child.accessProtected());
// 以下代码会报错,因为不能在类外部访问 protected 成员
// console.log(child.protectedProperty);
// console.log(child.protectedMethod());