受保护的成员访问java中不同的包 - 一个好奇心 [英] Protected member access from different packages in java - a curiosity

查看:83
本文介绍了受保护的成员访问java中不同的包 - 一个好奇心的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

package packageOne;
public class Base
{
protected void display(){
system.out.println("in Base");
}
}


package packageTwo;
public class Derived extends packageOne.Base{
public void show(){
new Base().display();//this is not working throws compilation error that display() from the type Base is not visible
new Derived().display();//is working
display();//is working
}
}

这两个包位于两个不同的文件中。但为什么会这样呢?

The two packages are in two different files. But why this behaviour?

推荐答案

http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.6

class C
    protected member;

// in a different package

class S extends C 

    obj.member; // only allowed if type of obj is S or subclass of S

动机可能如下。如果 obj S ,则类 S 有足够的知识它的内部,它有权操纵其成员,它可以安全地执行此操作。

The motivation is probably as following. If obj is an S, class S has sufficient knowlege of its internals, it has the right to manipulate its members, and it can do this safely.

如果 obj 不是 S ,它可能是 C S2 >, S 不知道。 S2 甚至可能在写入 S 时出生。对于 S 来操纵 S2 的受保护内部是非常危险的。如果这是允许的,从 S2 的角度来看,它不知道谁将篡改其受保护的内部以及如何,这使得 S2 很难说明自己的状态。

If obj is not an S, it's probably another subclass S2 of C, which S has no idea of. S2 may have not even been born when S is written. For S to manipulate S2's protected internals is quite dangerous. If this is allowed, from S2's point of view, it doesn't know who will tamper with its protected internals and how, this makes S2 job very hard to reason about its own state.

现在如果 obj D D延伸S ,对于 S 是危险的访问 obj.member ?并不是的。如何 S 使用成员 S 的共享知识和所有子类,包括 D S 因为超类有权定义行为,而 D 因为子类有义务接受和遵守。

Now if obj is D, and D extends S, is it dangerous for S to access obj.member? Not really. How S uses member is a shared knowlege of S and all its subclasses, including D. S as the superclass has the right to define behaviors, and D as the subclass has the obligation to accept and conform.

为了便于理解,该规则应该简化为要求 obj 的(静态)类型取值。毕竟,子类 D 出现在 S 中非常不寻常且不合适。即使它发生了, obj 的静态类型是 D ,我们的简化规则可以轻松处理它upcasting:((S)obj).member

For easier understanding, the rule should really be simplified to require obj's (static) type to be exactly S. After all, it's very unusual and inappropriate for subclass D to appear in S. And even if it happens, that the static type of obj is D, our simplified rule can deal with it easily by upcasting: ((S)obj).member

这篇关于受保护的成员访问java中不同的包 - 一个好奇心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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