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();
Get Java For Dummies Quick Reference now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.