Two syntax questions about arrays and classes


#1

Hi

Apologies if these are newbie questions. I have just begun processing.

(The full code is at the end of the post.)

Question 1: When initialising an array with a “for” loop, why do I have to do so within void setup()? Why can’t I do this before void setup()? That is to say, why can’t I write the following:

Class[] array = new Class[10];
for(int i = 0; i < array.length; i = i + 1) {
array[i] = new Class(0, i*50);
}
void setup() {
size(500, 500);
}

Question 2: When defining a class, why do I have to declare the class’ variables before the constructor? Why can’t I do this within the constructor? That is to say, why can’t I write the following:

class Class {
Class(int tempX, int tempY) {
int X = tempX;
int Y = tempY;
}

Thanks in advance.

The full code:

Class[] array = new Class[10];
void setup() {
size(500, 500);
for(int i = 0; i < array.length; i = i + 1) {
array[i] = new Class(0, i*50);
}
}
void draw() {
background(255);
for(int i = 0; i < array.length; i = i + 1) {
array[i].composeNmove(i);
}
}
class Class {
int X;
int Y;
Class(int tempX, int tempY) {
X = tempX;
Y = tempY;
}
void composeNmove(int change) {
fill(255);
ellipseMode(CENTER);
ellipse(X, Y, 50, 50);
X = X + change;
if (X >500) {
X = 0; 
}
}
}

#2

Actually we can! Just wrap those statements within a curly braces block:

Class[] array = new Class[10];

{
  for (int i = 0; i < array.length; ++i) {
    array[i] = new Class(0, i*50);
  }
}

Those are called initialization blocks btW.
And they’re run before their class’ constructors, together w/ field declarations.
Statements outside any initialization blocks, functions and field declarations aren’t allowed in Java.

Class’ variables are called fields in Java.
In Java, all class members need to be well-defined.
Members can’t be added on-the-fly to a class later.
And variables declared within methods aren’t fields, but local variables.


#3

An easy way to think about this: Anything that is defined in curly brackets, stays in the curly brackets.

So, if you have a pair of { and } brackets, anything that is defined inside of them, regardless of what these brackets mean, can only be accessed from within these brackets, and is essentially lost and then eventually garbage-collected by Java when it gets to that }.

Obviously this doesn’t apply if you modify something that was made before curly brackets, which is why answer to the first question by @GoToLoop works.
I mean, it probably doesn’t, but it’s helpful and easier to think about it that way.

Also, you can define your array as:

Class[] array = {new Class(0,0), new Class(0,50), new Class(0,100) }; //...

And, uh, in that case, brackets count as you are modifying that array you created outside of them, not defining new things.