overexchange
overexchange

Reputation: 1

What is Identity and state of "java.lang.Enum" type objects in java?

In the below code,

class Example{}
Example ex1 = new Example();
Example ex2 = new Example();
bool compareAddress = (ex1 == ex2);

here, compareAddress gives false, because identity is the memory address of an object pointed byex1 and ex2. field values(if any) within object of type class Example{} define state of that object.

But in the below code,

enum Company{
    EBAY(30), PAYPAL(10), GOOGLE(15), YAHOO(20), ATT(25);
    private int value;

    private Company(int value){
        this.value = value;
    }

}
Company x1 = Company.EBAY;
Company x1 = Company.EBAY;
bool compareValues = (x1 == x2);

here, compareValues gives true.

So, What is the identity and state of an object pointed by x1 and x2?

Upvotes: 0

Views: 113

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280102

An enum is a special type of class.

For example

enum Company {
    EBAY
}

will compile to

final class Company extends Enum<Company> {
    public final static Company EBAY = new Company(); // almost, this constructor invocation will have arguments
}

The field EBAY will, for the remainder of the Java process' life, hold the same reference value, which is a reference to a Company instance.

From the JLS,

Because there is only one instance of each enum constant, it is permitted to use the == operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant.

Upvotes: 4

Related Questions