为什么这段代码错了,而果壳中的Java是这样说的? [英] Why this code is wrong and Java in a Nutshell said so?

查看:77
本文介绍了为什么这段代码错了,而果壳中的Java是这样说的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在简单地阅读了Java,我在一个Nutshell中遇到了一个关于Java的问题。这个例子来自这本书。请参阅:
例如:

I read Java in a nutshell now, and I met a Question about Java in a Nutshell. This Example come from the book. See: e.g.:

package de;
public class A
{
    protected String x;
}

package uk;
import de.*;

class B extends A 
{
//First One
    public String getX(A a)
    {
        return "getX works" + a.x;//ERROR: x has protected access in A
    }  
//Second One
    public String getX(B b)
    {
        return "getX works" + b.x; // WORKS!
    }  

}

作者意味着因为B无权访问A.
的仲裁实例如果我们更改为第二个代码,那么编译器很高兴,因为相同类型的实例总能看到
彼此受保护领域。
我无法理解作者的意思,实际上是什么?

The Author means that because instances of B do not have access to arbitary instances of A. And if we change to the code like the second one, then the compiler is happy, because instances of the same exact type can always see each other’s protected fields. I can not understand the author's meaning, what is that actually?

推荐答案

B延伸A.
x受A保护。
所以B可以访问B中的x。

B extends A. x is protected in A. So B can access x's in B's.

但是B不能访问A中的x(不是B)。

B can however not access x's in A's (that are not B's).

考虑一个扩展A的C类。

Consider a class C that extends A.

你能看到B的背后的推理(Objecte Oriented原则)吗? t访问C的x。

Can you see the reasoning (Objecte Oriented principle) behind that B's can't access C's x's.

这篇关于为什么这段代码错了,而果壳中的Java是这样说的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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