Reference Types
A reference type is a data type that’s based on a class rather than on one of the primitive types that are built in to the Java language. The class can be a class that’s provided as part of the Java API class library or a class that you write yourself. Either way, when you create an object from a class, Java allocates the amount of memory the object requires to store the object. Then, if you assign the object to a variable, the variable is actually assigned a reference to the object, not the object itself. This reference is the address of the memory location where the object is stored.
To declare a variable using a reference type, you simply list the class name as the data type. For example, the following statement defines a variable that can reference objects created from a class named Ball
:
Ball b;
To create a new instance of an object from a class, you use the new
keyword along with the class name:
Ball b = new Ball();
Consider these statements:
Ball b1 = new Ball();
Ball b2 = b1;
Here, both b1
and b2
refer to the same instance of the Ball
class.