Студопедия
Случайная страница | ТОМ-1 | ТОМ-2 | ТОМ-3
АрхитектураБиологияГеографияДругоеИностранные языки
ИнформатикаИсторияКультураЛитератураМатематика
МедицинаМеханикаОбразованиеОхрана трудаПедагогика
ПолитикаПравоПрограммированиеПсихологияРелигия
СоциологияСпортСтроительствоФизикаФилософия
ФинансыХимияЭкологияЭкономикаЭлектроника

Objects and references

Data in a program (variables and literals) | Operations on data (operators and expressions) | Fundamentals of programming II | Write down and run this program on your computer | Write down and run this program on your computer | Introduction to objects | The first program | Types. Primitive types. | Types of variables. Declarations. | More on operators and expressions |


Читайте также:
  1. Additional references about literature for children
  2. Article 161. Violation of citizens' equality based on their race, nationality or religious preferences
  3. Bibliography and references......................................... 68
  4. Classes and objects
  5. Defining attributes of objects
  6. Defining operations on objects (methods)
  7. Direct objects

Except for operations on numbers, programming in Java consists in using objects. Objects are instances of classes.
For example, strings (sequences of characters) are objects of the class String, which defines common properties of objects of this type. The class String is one of many ready-to-use standard classes included in the Java 2 SDK environment. A programmer may define his or her own classes (soon we will see how to do this). He or she may also use classes defined by other programmers (not necessarily included in Java 2 SDK).
Recall that we use objects to call (invoke) their methods (in other words: to send messages to objects) which are a special kind of functions.

Let us assume that someone has created a class called Pair. Its objects represent pairs of integers - each object is made up of two elements which are integer numbers (first and second component of a pair).
What we can do with objects of the class Pair is specified by the set of methods of this class. Assume further that the following methods are defined in the class Pair (i.e. its objects understand the following messages):

This information is enough to use objects of the class Pair (we will learn its definition in the following lectures).

What should we do to set the value of a pair and print it to the command prompt?

Firstly, we must create a variable referencing an object which represents a pair.
Secondly, we must create an object of the class Pair.
Thirdly, we must send messages (set and show) to this object.

Here is the program:

public class PairSetAndShow { public static void main(String[] args) { Pair pair1 = new Pair(); // 1 pair1.set(1, 2); // 2 pair1.show(); // 3 }}

and its output:

(1, 2)


What is going on here:

What does the expression "object referenced by the variable pair1" mean? Why don't we say "an object pair1" although we do say "an integer number x"? What really is the variable pair1?
As we have seen, it was declared. But there appeared some strange formula creating an object.
What happens if we simply write:

Pair pair1;
pair1.set(1, 2);
pair1.show();

As stated earlier, declarations of variables referencing objects are noted analogously to declarations of variables of primitive types.

int x; // declaration of a variable of type int
Pair p; // declaration of a variable p which holds a reference to an object of the class Pair

However, there is a subtle semantic distinction between these two declarations.

The declaration of the variable x allocates memory to storing an integer (4 bytes). Thus x is a synonym for a data unit - an integer number.
After the assignment x = 4; to the location in memory denoted by x the value 4 is stored. This situation is depicted on the figure:

A declaration of a numeric variable x creates an "object" in memory - an integer number (before its value is explicitly set, it has some default value - mostly 0).

By the declaration of a variable holding reference to an object of some class the situation is completely different. Such a declaration does not create any object (it does not allocate memory for storing the object).
The object must be created using the expression new.
Its application results in the allocation of memory space for objects. The memory is allocated in its dynamic part (changing during the execution of a program) called heap.
The value of the new expression is the location in memory of the created object. This location can be stored in the variable, which is then used to manipulate object.

Thus, the declaration:

Pair p;

does not create any object of the class Pair.

And if there is no object, we cannot send any messages to it. That is why p.set(...) and p.show() are incorrect calls.

The variable p does not store any object.
However it may hold its location called also a reference to an object.

A reference is a value denoting location of an object in memory.

 

An object of the class Pair may be created using the expression new Pair(). By storing its value to the variable p, we gain the possibility to manipulate this object:

Pair p;
p = new Pair();

It may be noted simpler using the initializer:

Pair p = new Pair();


The following figure explains the problem:

where:

  1. Allocation of memory space for the variable p storing a reference to an object. The value of the reference is null which means it does not refer to any existing object.
  2. Evaluation of the expression new results in allocation of heap storage for the object of the class Pair (using some available address, here: 1304). The size of the allocated space is big enough to store two integer numbers (the components of the pair). Now both components have values 0.
  3. The value of the expression new is reference (or address 1304 in other words). It is stored in the memory space allocated for the variable p.
  4. The variable p has the value of the reference to the object of the class Pair. In step 2 this object was allocated on the heap under the address 1304.

 

Thus, the variable p holds a reference to the object of the class Pair.
As it was noted earlier, a variable p may refer to an object of the class Pair. But it does not always hold a reference to an existing object. After a declaration, but before its initialization, a variable does not hold any reference because no object has been created yet.

Now the question arises: what is the type of the variable p? In general: what is the type of variables denoting objects?

In Java, besides numeric types and boolean type there is just one more type: the reference type.

All variables declared with a class name in place of a type name are of reference type. Such variables may hold references to existing objects or they hold no reference at all.

 

If a variable of the reference type does not hold any reference to an object its value is null which is a keyword of the language.

Thus, acceptable values for variables of reference type are references to objects or null.
Similarly to 1 which is a literal of type int - null is the literal of reference type.

References are comparable:

To a variable of reference type value of another reference or null can be assigned.

One must remember that the above operations carried out on variables denoting objects (references) act on references themselves, not objects they refer to. Operations on objects are carried out by means of method invocations (using the dot operator).


Assume we want to carry out similar operations on two data elements being integer numbers and another two being objects of the class Pair:

  1. set the value of the first data element and set the value of the second data element
  2. assign to the variable denoting the second data element the value of the variable denoting the first data element.
  3. modify the value of the second data element
  4. compare variables denoting both data elements

Additionally (in both cases) we introduce the third data element whose value will be set to the value of the second data element. Then we compare the variables denoting these data elements (the second and the third).
Here is the program:

public class Difference { public static void main(String[] args) { // Operations on variables of primitive types int x, y, z; x = 3; y = 4; x = y; y = 5; z = 5; System.out.println("x = " + x); System.out.println("y = " + y); System.out.println("z = " + z); if (x == y) System.out.println ("x and y are equal."); else System.out.println ("x and y are not equal."); if (y == z) System.out.println ("y and z are equal."); else System.out.println ("y and z are not equal."); // Analogous operations on variables of reference type Pair px = new Pair(), py = new Pair(), pz = new Pair(); px.set(3, 3); py.set(4, 4); pz.set(5, 5); px = py; py.set(5, 5); System.out.print("Pair px: "); px.show(); System.out.print("Pair py: "); py.show(); System.out.print("Pair pz: "); pz.show(); if (px == py) System.out.println ("px and py equal."); else System.out.println ("px and py are not equal."); if (py == pz) System.out.println ("py and pz equal."); else System.out.println ("py and pz are not equal."); }}

x = 4
y = 5
z = 5
x and y are not equal.
y and z are equal.
Para px: (5, 5)
Para py: (5, 5)
Para pz: (5, 5)
px and py are equal.
py and pz are not equal.

The output of the program may be a surprise for those, who do not understand the differences between operations on variables of primitive types and of the reference type. The following observations clarify the program's output:

What has happened to the object with the values of elements [4,4] which was initially referenced by the variable py? This object was allocated on the heap with the expression py = new Pair(), so it occupies some space in memory. Afterwards values of its elements were modified (py.set(4,4)), so these values were stored into that memory space. Then to the variable py the value of the variable px was assigned. Thus there are no references to this object left in the program. Because objects can be accessed only using references, this object is no longer accessible. However, it occupies some space. Should we worry about it? If there appeared more such objects in memory, would it cause memory overflow?

Fortunately it would not.

Unused objects (which are not referenced by any variable) are removed from the memory automatically by the garbage collector.

 

Let us sum up:

 

 


Дата добавления: 2015-11-16; просмотров: 78 | Нарушение авторских прав


<== предыдущая страница | следующая страница ==>
Numeric promotions| The class String

mybiblioteka.su - 2015-2024 год. (0.009 сек.)