对象是否封装数据,以便即使是同一类的其他实例也无法访问数据? [英] Do objects encapsulate data so that not even other instances of the same class can access the data?

查看:109
本文介绍了对象是否封装数据,以便即使是同一类的其他实例也无法访问数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,

对象是否封装数据,以便即使是同一类的其他实例也无法访问数据?只有在使用关键字private时?什么是Java中的访问器方法 - 像getName()这样的方法?

Do objects encapsulate data so that not even other instances of the same class can access the data? Only when the keyword "private" is used? What are "accessor methods" in Java - methods like getName()?

谢谢

推荐答案

我不倾向于用一个对象来访问另一个对象,而是代码可以访问其中的哪些数据对象。

I don't tend to think of it in terms of one object having access to another, but rather what code has access to what data within an object.

在Java(和C#,btw)中,类中的代码可以访问同一类的任何对象的私有成员。然后你就拥有了程序包/程序集访问权限和公共访问权限。

In Java (and C#, btw) code within a class has access to the private members of any object of the same class. Then you've got package/assembly access and public access.

棘手的是受保护的访问,这是的访问代码子类 - 但它取决于目标对象:只允许访问对象的受保护成员,如果它是与代码位置相同类型的实例,或某些子类 - 即使它是暴露由父类。例如,假设你有:

The tricky one is protected access, which is sort of access to code in subclasses - but it depends on the target object: you're only allowed to access protected members of an object if it's an instance of the same type as the location of the code, or some subclass - even if it's being exposed by a parent class. So for instance, suppose you had:

class Parent
{
    protected int x;
}

class Child1 extends Parent
class Child2 extends Parent
class Grandchild extends Child1

然后在 Child1 代码中,您可以访问 Parent.x 仅适用于已知(在编译时)为 Child1 孙子的实例的对象。例如,您不能使用 new Parent()。x new Child2()。x

Then within the Child1 code, you can access Parent.x only for objects which are known (at compile-time) to be instances of Child1 or Grandchild. You couldn't, for instance, use new Parent().x or new Child2().x.

这篇关于对象是否封装数据,以便即使是同一类的其他实例也无法访问数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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