devxlogo

Obtaining a Reference to an Object

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.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist