Reputation: 1
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
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 theequals
method when comparing two object references if it is known that at least one of them refers to anenum
constant.
Upvotes: 4