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

查看:294
本文介绍了在Java中,为什么super-class方法不能从子类实例访问受保护的或私有的方法/变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们从另一个行为开始:即使你将方法/变量声明为私有,同一个类的另一个实例也可以访问它。没关系,我可以住它。

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

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

Now the question part: For example, in 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 "NULL" string.

我在反射中运行变量并获取它们的值。但是如果我扩展我的类和添加私人甚至受保护的变量,我的基类不能访问它们。我必须在变量上setAccessible,然后才能使用它。

I run through the variables in 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 it.

因此,请向我解释为什么基类(超类)不能访问私有/ protected变量从它的子类。它是它的子类,所以我不能得到它。这是什么意思?

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

我知道超类不应该知道它是子类,但在我的例子中,这是有道理的,不是吗?

I know that super-class should not know about it's 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 accessing another instance's private variables from the same class instance isn't considered 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中,为什么super-class方法不能从子类实例访问受保护的或私有的方法/变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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