Java referencing objects in array

Objects. Creating and saving the objects of classes. Areas of data storage in memory. Using an arrays of references to objects

Java uses a single syntax for working with objects. A class object is declared using a reference.

The general form of declaring a class object without allocating memory for it has the following form:

  • ClassName – class name for which an object named objName is created;
  • objName – the name of the reference to the ClassName object.

The above declaration indicates that the objName is a reference to a ClassName object. For the reference you need to allocate memory (initialize the reference) using the new operator as shown below:

objName = new ClassName();

If you do not allocate memory for the reference and refer to it as a class object, an error will occur.

There is another general form for declaring a class object. In this case, the memory is allocated when the object is declared:

ClassName objName = new ClassName();

The allocation of memory for a reference to a class object is also called “attaching” an object to a reference.

2. Examples of creating the objects of different classes

Example 1. Create a CLine class object that implements the line on the coordinate plane. The program code for the class declaration is:

// class that implements a line on the coordinate plane public class CLine < // internal variables  private double x1, y1, x2, y2; // class constructors // constructor without parameters CLine() < x1 = y1 = 0; x2 = y2 = 1; > // constructor with 4 parameters CLine(double x1, double y1, double x2, double y2) <  this.x1 = x1; this.y1 = y1;  this.x2 = x2; this.y2 = y2; > // access methods // get data  public double GetX1() < return x1; >  public double GetY1() < return y1; >  public double GetX2() < return x2; >  public double GetY2() < return y2; > // set data void SetXY(double nx1, double ny1, double nx2, double ny2) < x1 = nx1; y1 = ny1; x2 = nx2; y2 = ny2; > // A method that calculates the length of a line  double Length() < double len; len = Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2)); return len; > >

The following code shows how to create and use CLine objects.

public class CTestLine <  public static void main(String[] args) <  double x, y; // additional variables // creating a CLine class object using a constructor without parameters CLine line1 = new CLine(); // creating a CLine class object using a constructor with 4 parameters CLine line2 = new CLine(2.0, 3.0, 4.0, 5.0); // using objects of line1 class x = line1.GetX1(); // x = 0.0 y = line1.GetY2(); // y = 1.0 // using objects of line2 class x = line2.GetX1(); // x = 2.0 x = line2.GetX2(); // x = 4.0 y = line2.GetY2(); // y = 5.0 // redefining the line1 object, the previous object will be destroyed using the "garbage collector" line1 = new CLine(-4.0, -2.0, 33.4, -20.5); x = line1.GetX1(); // x = -4.0 y = line1.GetY2(); // y = -20.5 > >

As you can see from the code, in the main() function two references with the names line1 , line2 are declared for CLine objects. Memory is allocated for these references using the ‘new’ statement. Then, for the line2 object, the memory is redefined again. The old memory will be freed with the next of garbage collection.

Example 2. Create a CName class object that implements the name. The main() function demonstrates the creation of a CName class object in different ways using different constructors.

// class that implements the name public class CName < private String name; private String surname; private String patronymic; // class constructors // constructor without parameters CName() < name = surname = patronymic = ""; > // constructor with three parameters CName(String _name, String _surname, String _patronymic) < name = _name; surname = _surname; patronymic = _patronymic; > // access methods String GetName() < return name; > String GetSurname() < return surname; > String GetPatronymic() < return patronymic; > // function that demonstrates the use of the CName class  public static void main(String[] args) < CName nm1 = new CName(); // the constructor without parameters is called CName nm2; // just declaring a reference to an object of the CName class, the memory has not yet been allocated nm2 = new CName("Happy", "New", "Year!"); // creating an object - allocating memory // checking String str; str = nm1.GetName(); // str = "" str = nm1.GetSurname(); // str = "" str = nm2.GetName(); // str = "Happy" str = nm2.GetSurname(); // str = "New" str = nm2.GetPatronymic(); // str = "Year!" > >
3. What are the areas of data storage in Java programs?

In Java for storing data (objects) there are 5 different repositories:

  • registers. In this case, the data is stored inside the processor. In the registers, the data are processed most quickly. However, the number of registers is strictly limited. The compiler uses registers as needed. In Java, there are no immediate commands to store all data in registers only. Even in powerful C/C ++ languages, instructions for placing data in registers are only recommended;
  • stack. For the program, the stack is placed in the common RAM. The stack is organized using stack pointers. The stack operates on the principle of LIFO (Last-In-First-Out). Such an organization is convenient when you need to allocate memory for local functions (methods) of different levels of attachments. The stack contains only pointers to objects. The objects themselves are placed in the “heap”. The stack pointer moves downward if you want to allocate memory, and upward if the memory is freed. Thus, in terms for speed, the stack is second after registers. However, the stack does not possess such flexibility as the “heap”, since the compiler needs to know the life cycle of the data placed on the stack;
  • heap. This is a general-purpose storage that resides in RAM. All objects (instances of objects) of Java are stored here. “Heap” is more flexible compared to the stack. This is because the compiler does not spend extra effort on determining the duration of existence of objects in the “heap”. In the program, an object is created using the new operator. As a result, memory is allocated in the “heap”. However, allocating memory from the “heap” takes longer than the stack. It should be noted that powerful C/C ++ languages support the explicit creation of objects on the stack as well as in the “heap”;
  • permanent repository. Programs often use data that is unchanged. These data include constants (for example, string constants). It is advisable to embed these data directly into the code of the program. Sometimes constants are placed in static memory (ROM);
  • external repository. External storage can be permanent storage devices, for example, a computer hard drive or storage data of remote computers on the network. This type of data saving allows you to save objects on storage media, and then restore them to save in RAM.
4. In which area of memory are objects and object references stored?

Objects are stored in the “heap”. References to objects are stored in the stack.

5. How in Java are created and stored arrays of objects?

Unlike C/C ++, an array in Java is necessarily initialized. Access outside the array is not possible. To create an array of objects, you need to use a record like this:

  • ClassName – The name of a class that serves as the type for array of objects arrayObj ;
  • arrayObj – the name of the array of objects.

In the above code, the array of references arrayObj to objects of class ClassName is declared. To allocate memory for an arrayObOj from an array of 10 elements of type ClassName, you would write:

arrayObj = new ClassName[10];

This can be done in another way, immediately when declaring an array:

ClassName arrayObj = new ClassName[10];

Memory is allocated only for the array of references. For objects, memory is not yet allocated. To allocate memory for any object, you need to use approximately the following code:

for (int i=0; inew ClassName(); >

In the above example, memory is allocated for any object in the array of objects arrayObj . To determine the length of an array, use the length property, which is public for all kinds of arrays in Java.

6. Example of declaring and initializing an array of objects

Let the class CLine be given, the implementation of which is described in p. 2. The example demonstrates the use of an array of n objects of the CLine type. The value of n is specified programmatically ( n = 10).

public class CTestLine <  public static void main(String[] args) <  int n = 10; CLine[] arrayLines = new CLine[n]; // allocating memory for an array of references // allocating memory for each element of the array for (int i=0; i// allocating memory and initializing each individual element of the array arrayLines[i] = new CLine(i*2, i*1.5, i+2.2, i-1); > // the use of an array, the calculation of the total length of all segments  double sumLength = 0;  for (int i=0; iout.println("Sum color: #008000;">// Sum = 45.45345204172149 > >

Источник

Can we store objects in an array in Java?

Array is a container which can hold a fix number of items and these items should be of the same type. Most of the data structures make use of arrays to implement their algorithms. Following are the important terms to understand the concept of Array.

  • Element: Each item stored in an array is called an element.
  • Index: Each location of an element in an array has a numerical index, which is used to identify the element.

Storing Objects in an array

Yes, since objects are also considered as datatypes (reference) in Java, you can create an array of the type of a particular class and, populate it with instances of that class.

Example

Following Java example have a class named Std and later in the program we are creating an array of type Std, populating it, and invoking a method on all the elements of the array.

class Std < private static int year = 2018; private String name; private int age; public Std(String name, int age)< this.name = name; this.age = age; >public void setName(String name) < this.name = name; >public void setAge(int age) < this.age = age; >public void display() < System.out.println("Name: "+this.name); System.out.println("Age: "+this.age); System.out.println("Year: "+Std.year); >> public class Sample < public static void main(String args[]) throws Exception < //Creating an array to store objects of type Std Std st[] = new Std[4]; //Populating the array st[0] = new Std("Bala", 18); st[1] = new Std("Rama", 17); st[2] = new Std("Raju", 15); st[3] = new Std("Raghav", 20); //Invoking display method on each object in the array for(int i = 0; i> >

Output

Name: Bala Age: 18 Year: 2018 Name: Rama Age: 17 Year: 2018 Name: Raju Age: 15 Year: 2018 Name: Raghav Age: 20 Year: 2018

Источник

Can we store objects in an array in Java?

Array is a container which can hold a fix number of items and these items should be of the same type. Most of the data structures make use of arrays to implement their algorithms. Following are the important terms to understand the concept of Array.

  • Element: Each item stored in an array is called an element.
  • Index: Each location of an element in an array has a numerical index, which is used to identify the element.

Storing Objects in an array

Yes, since objects are also considered as datatypes (reference) in Java, you can create an array of the type of a particular class and, populate it with instances of that class.

Example

Following Java example have a class named Std and later in the program we are creating an array of type Std, populating it, and invoking a method on all the elements of the array.

class Std < private static int year = 2018; private String name; private int age; public Std(String name, int age)< this.name = name; this.age = age; >public void setName(String name) < this.name = name; >public void setAge(int age) < this.age = age; >public void display() < System.out.println("Name: "+this.name); System.out.println("Age: "+this.age); System.out.println("Year: "+Std.year); >> public class Sample < public static void main(String args[]) throws Exception < //Creating an array to store objects of type Std Std st[] = new Std[4]; //Populating the array st[0] = new Std("Bala", 18); st[1] = new Std("Rama", 17); st[2] = new Std("Raju", 15); st[3] = new Std("Raghav", 20); //Invoking display method on each object in the array for(int i = 0; i> >

Output

Name: Bala Age: 18 Year: 2018 Name: Rama Age: 17 Year: 2018 Name: Raju Age: 15 Year: 2018 Name: Raghav Age: 20 Year: 2018

Источник

Читайте также:  Java литература с задачами
Оцените статью