java私有成员的访问,私有成员访问Java

本文解析了Java中私有成员访问权限:若在类级别定义,私有成员仅限类内访问;若在对象级别,仅对象实例内部可访问。DevSolar提到,从Java 7开始,类型变量的私有成员不允许外部直接访问。实例演示了如何理解并应用这些规则。
摘要由CSDN通过智能技术生成

Is the private member access at the class level or at the object level. If it is at the object level, then the following code should not compile

class PrivateMember {

private int i;

public PrivateMember() {

i = 2;

}

public void printI() {

System.out.println("i is: "+i);

}

public void messWithI(PrivateMember t) {

t.i *= 2;

}

public static void main (String args[]) {

PrivateMember sub = new PrivateMember();

PrivateMember obj = new PrivateMember();

obj.printI();

sub.messWithI(obj);

obj.printI();

}

}

Please clarify if accessing the member i of obj within the messWithI() method of sub is valid

解决方案

As DevSolar has said, it's at the (top level) class level.

Otherwise, if the member or

constructor is declared private, then

access is permitted if and only if it

occurs within the body of the top

level class (§7.6) that encloses the

declaration of the member or

constructor.

Note that there's no indication that it's restricted to members for a particular object.

As of Java 7, the compiler no longer allows access to private members of type variables. So if the method had a signature like public void messWithI(T t) then it would be a compiler error to access t.i. That wouldn't change your particular scenario, however.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值