Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does object identity mean in java?

Tags:

java

object

oop

I was reading about "Data abstraction" in java language programming that I faced with this phrase:

Objects in java are characterized by three essential properties: state, identity, and behavior. 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 ?

like image 936
daniel nasiri Avatar asked Aug 02 '17 06:08

daniel nasiri


2 Answers

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). In this case, it happens both have the same state (42).

  • e1 and e2 have behavior: A method, showValue, that will dump out their value to the console. (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.)

  • e1 and e2 have identity: The expression e1 == e2 is false; 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.

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.)

like image 190
T.J. Crowder Avatar answered Oct 23 '22 23:10

T.J. Crowder


I can think in these two examples from the C++ world.

Example 1: objects a and b are not identical, because they don't share the same memory.

Someclass a;
Someclass b;

Example 2: objects a and b are identical because they point to the same object.

Someclass c;
Someclass* a = &c;
Someclass* b = &c;
like image 1
Francisco Rodríguez Avatar answered Oct 23 '22 22:10

Francisco Rodríguez