Reputation: 5167
I have a main class with a couple of public constant variables, and I have a custom class, I would like to know how can I access the constants of the main class from the custom class?
Main Class code:
import processing.core.*;
import toxi.geom.*;
import toxi.math.*;
public class VoronoiTest extends PApplet {
// this are the constants I want to access from the Site class
public static int NUM_SITES = 8;
public static int SITE_MAX_VEL = 2;
public static int SITE_MARKER_SIZE = 6;
Site[] sites;
public void setup() {
size( 400, 400 );
sites = new Site[NUM_SITES];
for ( int i = 0; i < sites.length; i++) {
sites[i] = new Site( this );
}
}
}
And this is the Site class code:
import processing.core.*;
public class Site {
PApplet parent;
float x, y;
PVector vel;
int c;
Site ( PApplet p ) {
parent = p;
// here I try to get the constants from the main class
vel = new PVector( parent.random(-parent.SITE_MAX_VEL, SITE_MAX_VEL), parent.random(-SITE_MAX_VEL, SITE_MAX_VEL) );
}
}
Any help will be much appreciated!
Upvotes: 1
Views: 7195
Reputation: 97571
You can't. Because parent
is of type PApplet
, not VoronoiTest
, you cannot guarantee that it has the static member SITE_MAX_VEL.
Conversely, if parent
were of type VoronoiTest
, there would be little point in accessing the static variable through the instance, as it would be impossible for it to change.
As already mentioned, to access static members, use the ClassName.STATIC_MEMBER
notation (in this case, VoronoiTest.SITE_MAX_VEL
).
Better yet though, just store the constants in the Site
class instead. After all, that seems the most logical place for them.
import processing.core.*;
public class Site {
public static final int COUNT = 8;
public static final int MAX_VEL = 2;
public static final int MARKER_SIZE = 6;
PApplet parent;
float x, y;
PVector vel;
int c;
Site(PApplet p) {
parent = p;
vel = new PVector(
parent.random(-MAX_VEL, MAX_VEL),
parent.random(-MAX_VEL, MAX_VEL)
);
}
}
Upvotes: 3
Reputation: 13079
Static fields are accessed via the class-name. Use VoronoiTest.SITE_MAX_VEL
.
Upvotes: 0
Reputation: 4951
Use the VoronoiTest reference. VoronoiTest.SITE_MAX_VEL, for example. When you use a PApplet reference, the compiler doesn't have any way of knowing that the static variables exist.
Upvotes: 0