Assigning Objects

Is an object a reference?

Assigning objects is pretty important in Java. In Java you have two different types of data types. primitive data types (byte, char, short, int, long, float, double, boolean) and you have reference data types. Objects are reference data types. The content of a reference data type is an address to where the data is stored.

In order to do this first we have to allocate the variable in memory.

// Assigning Objects
Cellphone android;

Above Cellphone is the class we are going to reference and android is the name of the variable that is going to hold the reference to the object.

// Referencing a new object
android = new Cellphone("Samsung");

Here we create a new object of the class called Cellphone. We then send it a parameter Samsung. Then the variable android is given a link to the new object we created.

We can also allocate more then one variable at the same time.

// Two References to a single object
Cellphone samsung1, samsung2;

To reference a new object to samsung1 we do

samsung1 = new Cellphone("Samsung");

Then to assign the reference in samsung1 to samsung2

samsung2 = samsung1;

Leave a comment

Design a site like this with WordPress.com
Get started