I’m until now don’t know what is the actual use of private and final.
I think final is like const in C/C++. And private maybe like static.
This works fine for final and can’t be changed:
void print_static(){
final int a = 100;
println(a);
}
When I change it to private I get this error:
void print_static(){
private int a;
println(a);
}
Error:
Illegal modifier for parameter a; only final is permitted
So I guess I have to use a class to be able to use private. But I’m having some problems calling functions from a class. I don’t know what I’m missing here. I tried this:
public class class_example {
public void print_hi() {
println("Hi there!");
}
}
But output window freezes and I get error this error:
Even though Java (and other C-based languages like JavaScript) has a similar C syntax, not all C features are available; like pointer operators, static local variables, etc.
In Java we can have static fields, methods, classes; but neither local variables nor parameters can be declared static.
The general approach for Processing sketches is just declare global variables.
But if you prefer better separation of concerns you’re gonna need to create a class to place both the variables (fields) and their related functions (methods) grouped together as 1 structure, like @paulgoux already posted.
Here’s another example:
void setup() {
frameRate(1);
}
void draw() {
background((color) random(#000000));
print(Value.nextValue(), TAB);
}
static class Value {
static int a;
static int nextValue() {
return ++a;
}
}
Basically the name of the class Value becomes the global “variable” now.
So it isn’t that much better than vanilla global variables; unless you need so many global variables that grouping them in classes is the sane thing to do.
I actually did a simple example and I think I learned something.
static works in global and inside class only and doesn’t work inside a local function.
This is my example:
static class var_specs{
static int a = 9;
};
static int b = 90;
void setup(){
println(var_specs.a);
var_specs.a++;
println(var_specs.a);
//////////////////////////////////
println(b);
b++;
println(b);
}
void local_function(){
static int c = 88; // <---------------- here's the problem
c++;
println(c);
// it issues this error:
// --> Illegal modifier for parameter c; only final is permitted
}
That’s correct, at least in reference to processing. I think standard java doesn’t have this limitation.
Final is the equivalent of const, and defines a variable as unchangeable. Removing final should cause no problem to your original request. Just note you can use final, private public and protected. Read more about these on the java ref if you want to find out more.