Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 98

Using Reference Types

Оглавление

A reference type refers to an object (an instance of a class). Unlike primitive types that hold their values in the memory where the variable is allocated, references do not hold the value of the object they refer to. Instead, a reference “points” to an object by storing the memory address where the object is located, a concept referred to as a pointer. Unlike other languages, Java does not allow you to learn what the physical memory address is. You can only use the reference to refer to the object.

Let's take a look at some examples that declare and initialize reference types. Suppose we declare a reference of type String:

String greeting;

The greeting variable is a reference that can only point to a String object. A value is assigned to a reference in one of two ways:

 A reference can be assigned to another object of the same or compatible type.

 A reference can be assigned to a new object using the new keyword.

For example, the following statement assigns this reference to a new object:

greeting = new String("How are you?");

The greeting reference points to a new String object, "How are you?". The String object does not have a name and can be accessed only via a corresponding reference.

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

Подняться наверх