关于类私有成员访问规则的疑问:不同实例可互访私有成员?求示例
面向对象中私有成员跨实例访问规则解析
规则核心说明
构造函数私有参数的自动绑定:在TypeScript、Kotlin这类语言中,构造函数参数前加
private修饰符时,会自动完成两件事:- 声明类的私有成员变量(比如
this.x) - 将构造函数参数的值赋值给该成员变量
最终这个成员的可见性被设为私有:仅当前类的内部代码能读写,外部代码直接访问会报错。
- 声明类的私有成员变量(比如
跨实例访问私有成员:这是容易混淆的关键点——私有成员的可见性是基于「类」而非「实例」。也就是说:
- 同一个类的任意实例,都可以直接访问彼此的私有成员
- 子类、其他类的实例,哪怕是继承关系,也完全无法访问该类的私有成员
代码示例(TypeScript)
class Position { // 构造函数参数加private,自动创建私有成员this.x、this.y并完成赋值 constructor(private x: number, private y: number) {} // 对比当前实例与另一个Position实例的坐标 isSame(other: Position): boolean { // 直接访问other的私有成员x、y return this.x === other.x && this.y === other.y; } // 修改另一个Position实例的坐标 updateTarget(other: Position, newX: number, newY: number): void { other.x = newX; other.y = newY; } } // 测试逻辑 const posA = new Position(5, 10); const posB = new Position(5, 10); console.log(posA.isSame(posB)); // 输出: true posA.updateTarget(posB, 15, 20); console.log(posB.isSame(new Position(15, 20))); // 输出: true // 外部直接访问私有成员会触发编译错误 // console.log(posA.x); // 错误:属性“x”为私有属性,只能在类“Position”中访问
子类访问限制示例
class AdvancedPosition extends Position { constructor(x: number, y: number, public z: number) { super(x, y); } tryAccessParentPrivate(): void { // 子类无法访问父类的私有成员,以下代码会报错 // console.log(this.x); // 错误:属性“x”为私有属性,只能在类“Position”中访问 } }
Java版本示例(手动模拟自动赋值逻辑)
Java没有构造函数参数自动绑定的语法,但可以手动实现效果,同样能体现跨实例访问私有成员的规则:
public class Position { private int x; private int y; public Position(int x, int y) { // 手动完成参数赋值,对应自动绑定的效果 this.x = x; this.y = y; } public boolean isSame(Position other) { // 直接访问other的私有成员 return this.x == other.x && this.y == other.y; } public void updateTarget(Position other, int newX, int newY) { other.x = newX; other.y = newY; } public static void main(String[] args) { Position pos1 = new Position(5, 10); Position pos2 = new Position(5, 10); System.out.println(pos1.isSame(pos2)); // 输出: true pos1.updateTarget(pos2, 15, 20); System.out.println(pos2.isSame(new Position(15, 20))); // 输出: true // 外部访问私有成员会触发编译错误 // System.out.println(pos1.x); // 错误:x has private access in Position } }
内容的提问来源于stack exchange,提问作者ManojKS091
相关产品推荐
相关产品推荐

