私有方法不能被子类覆盖_在Java中,为什么超类方法不能从子类实例访问受保护的或私有的方法/变量?...

Let's start with another behavior: even if you declare a method/variable as private, another instance of the same class can access it. That's OK I can live with it. I call these class-private and not instance-private.

Now the question part:

For example, at runtime I want to be able to check that all String variables in this class are not null, and if they are null they should be changed to the string "NULL".

I can run through the variables using reflection and get their values. But if I extend my class and add private or even protected variables my base class can't access them. I have to setAccessible on the variables before I can use them.

So please explain to me why the base-class (super-class) can't access private/protected variables from its sub-class. It is its sub-class, so I don't get it. What's the idea behind this?

I know that the super-class should not know about its sub-classes, but in my example it makes sense, no?

Is it because I can't or shouldn't restrict my sub-classes in this way?

Update:

Based on the answers, I want to know also: Why isn't accessing another instance's private variables from the same class considered a violation of encapsulation?

解决方案

It's as simple as it's a violation of encapsulation. Another class should not be able to reach into your class and be messing around with things, even if you generalize that class. How does a Vehicle know anything about a Car for example? The whole point of a base class is to provide for the sub-classes, but like an over-protective parent, what you're suggesting would be too much.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值