Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Beginner
Jan 9, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Obtaining a Reference to an Object

In Java, you can obtain a reference to an object in three ways. First, you can obtain it from the new operation. The new operation instantiates an object of a particular class, and returns a reference to it. This reference is a handle to the location where the object resides in memory.
SomeObject aRef = new SomeObject();
The reference is stored in the variable "aRef."

Second, you can obtain a reference by assignment. The reference to an existing reference obtained by assignment is just a duplicate reference to the object (and not to a copy of the object).

SomeObject anotherRef = aRef;
The variable anotherRef duplicates aRef. Both references point to the same instance of the object of type SomeObject.

Third, you can obtain a reference by cloning an object. The reference that is returned by cloning an object is a new reference to a copy of the object.

SomeObject anotherObjectRef = aRef.clone();
The clone() method is defined in the Object class. It is a protected method so that derived classes of the Object class (which, in effect, is every other Java class) can override it. Once an object is cloned, two copies of the object exist with independent references. Changing one object does not automatically change the other. You can only call the clone() method on an object that extends the Clonable interface.
Ajit Sagar
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date