简体   繁体   English

对象标识在java中意味着什么?

[英]What does object identity mean in java?

I was reading about "Data abstraction" in java language programming that I faced with this phrase: 我正在阅读我在这个短语中遇到的java语言编程中的“数据抽象”:

Objects in java are characterized by three essential properties: state , identity , and behavior . java中的对象具有三个基本属性: 状态身份行为 The state of an object is a value from its data type. 对象的状态是其数据类型的值。 The identity of an object distinguishes one object from another . 对象的标识将一个对象与另一个对象区分开来 It is useful to think of an object's identity as the place where its value is stored in memory . 将对象的标识视为其值存储在内存中的位置很有用。

Can everyone explain more specifically what is the identity ? 每个人都可以更具体地解释什么是身份?

Suppose you have this simple class: 假设你有这个简单的类:

class Example {
    private int value;

    Example(int v) {
        this.value = v;
    }

    public void showValue() {
        System.out.println(this.value);
    }
}

And we have this code (for instance, in a method somewhere else): 我们有这个代码(例如,在其他地方的方法中):

Example e1 = new Example(42);
Example e2 = new Example(42);

Then: 然后:

  • e1 and e2 have state (their value member). e1e2具有状态 (它们的value成员)。 In this case, it happens both have the same state (42). 在这种情况下,它们都具有相同的状态(42)。

  • e1 and e2 have behavior : A method, showValue , that will dump out their value to the console. e1e2行为 :一个方法showValue ,它将把它们的值转储到控制台。 (Note that they don't necessarily have to have the same behavior: We could create a subclass of Example that did something different with showValue [perhaps showed it in a pop-up dialog box], and make e2 an instance of that subclass instead.) (注意,它们不一定必须具有相同的行为:我们可以创建一个Example的子类,它使用showValue不同的操作[也许在弹出的对话框中显示它],并使e2成为该子类的实例。)

  • e1 and e2 have identity : The expression e1 == e2 is false ; e1e2具有同一性 :表达式e1 == e2false ; they are not the same object. 它们不是同一个对象。 They each have a unique identity. 他们每个人都有独特的身份。 They may be equivalent objects (we could implement equals and hashCode such that they were deemed equivalent), but they will never have the same identity. 它们可能是等价的对象(我们可以实现equalshashCode ,使它们被认为是等价的),但它们永远不会具有相同的身份。

No object ever has the same identity as another object; 没有任何对象具有与另一个对象相同的身份; an object's identity is guaranteed unique within the memory of the running process. 在运行进程的内存中保证对象的标识是唯一的。

(They also have other characteristics, such as their class type, but those are the main three.) (它们还有其他特征,例如它们的类型,但那些是主要的三种。)

I can think in these two examples from the C++ world. 我可以从C ++世界的这两个例子中思考。

Example 1: objects a and b are not identical, because they don't share the same memory. 示例1:对象a和b不相同,因为它们不共享相同的内存。

Someclass a;
Someclass b;

Example 2: objects a and b are identical because they point to the same object. 示例2:对象a和b是相同的,因为它们指向同一个对象。

Someclass c;
Someclass* a = &c;
Someclass* b = &c;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM