在Java中,为什么超类方法不能从子类实例访问受保护的或私有的方法/变量? [英] In Java, why can't a super-class method access protected or private methods/variables from a sub-class instance?

查看:205
本文介绍了在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.

现在问题部分:
例如,在运行时我希望能够检查所有类中的字符串变量不为空,如果它们为null,则应将其更改为字符串NULL。

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".

我可以使用反射来运行变量并获取它们的值。但是如果我扩展我的类并添加私有甚至保护变量,我的基类就无法访问它们。在我可以使用它们之前,我必须对变量 setAccessible

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.

所以请向我解释为什么基础 - class(超类)无法从其子类访问私有/受保护变量。它是它的子类,所以我不明白。这背后的想法是什么?

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.

这篇关于在Java中,为什么超类方法不能从子类实例访问受保护的或私有的方法/变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆