Good day. I understand Java and the question arose:
If I make the connections array static and use it in the getElementOfArray() method, then with System.out.println(getElementOfArray()); it displays the (last) element of the array (which is what is needed).
But if I want the array to belong to an object and not to a class, and create a ConnectionManager object to access the array, then System.out.println(getElementOfArray()); displays only null .
Question:
- What object is created, at
ConnectionManager cm = new ConnectionManager(); - Will this object start with psvm
- Why is it that everything goes well with a static array, but not when creating an object?
thank you very much
public class ConnectionManager {
private Connection1 [] connections = new Connection1 [5]; // Array for Connection1
private static int counter;
private void fillArray () {
for (int i = 0; i <connections.length; i ++) {// Fills the array
connections [i] = Connection1.getInstance (); // elements of connection1
counter ++;
System.out.println (connections.getClass () + "Element added");
}
}
static Connection1 getElementOfArray () {
ConnectionManager cm = new ConnectionManager (); // Create an object
if (counter> 0) {
return cm.connections [- counter];
} else {
return null;
}
}
public static void main (String [] args) {
ConnectionManager cm = new ConnectionManager ();
cm.fillArray ();
System.out.println (getElementOfArray ());
}
}