| Java FAQ | ||
| JSP FAQ | ||
| Servlet FAQ | ||
XyzWs Java FAQ:
Can an object access a private member of another object of the same class?
Printer-friendly version |
Mail this to a friend
|
Advertisement
|
Can an object access a private member of another object of the same class?Yes, an object can access private instant members of other objects in the same class. Let's re-exam an example from "Why always override hashcode() if overriding equals()?" in XyzWs Java FAQ.
public class CustomerID {
private long crmID;
private int nameSpace;
public CustomerID(long crmID, int nameSpace) {
super();
this.crmID = crmID;
this.nameSpace = nameSpace;
}
public boolean equals(Object obj) {
//null instanceof Object will always return false
if (!(obj instanceof CustomerID))
return false;
if (obj == this)
return true;
return this.crmID == ((CustomerID) obj).crmID &&
this.nameSpace == ((CustomerID) obj).nameSpace;
}
public static void main(String[] args) {
Map m = new HashMap();
m.put(new CustomerID(2345891234L,0),"Jeff Smith");
System.out.println(m.get(new CustomerID(2345891234L,0)));
}
}
In the above example code, you can see that crmID and nameSpace are private fields. |