Classes initialising other classes

Hello!

This is more a Java question than processing but I’m hoping the processing folks will be more merciful that stack overflow :slight_smile: I am trying to translate this gravity simulator from python to processing.

I’m familiar with python and understand the program syntactically (if not mathematically) but I’m struggling with the Java syntax.

Below code is my attempt at a small chunk of the program. The first class is just to hold the state of each planet, the second class is the planet and should initiate an instance of the State class.

When the State class gets initiated in the Planet class’s constructor, it returns a Null when I try to print it. What am I doing wrong? (I expect lots…)

// not allowed globals in java
// so i put in the planet class

// int WIDTH = 900;
// int HEIGHT = 600;
// int PLANETS = 30;
// float DENSITY = 0.01;
// float GRAVITYSTRENGTH = 1.e4;


class State {

	//Class representing position and velocity.

	float x;
	float y;
	float vx;
	float vy;

	public State(float _x, float _y, float _vx, float _vy){
		println("init state");
		x = _x;
		y = _y;
		vx = _vx;
		vy = _vy;
	}
}

class Planet{

	/* Class representing a planet. The "_st" member is an instance of "State",
    carrying the planet's position and velocity - while the "_m" and "_r"
    members represents the planet's mass and radius. */

	int WIDTH = 900;
	int HEIGHT = 600;
	int PLANETS = 30;
	float DENSITY = 0.01;
	float GRAVITYSTRENGTH = 1.e4;
	ArrayList planets;
	State _st;


    public Planet(){
		//planets = listOfPlanets;
		println("init planet");
		State _st = new State(
			float(int(random(0, WIDTH))), 
			float(int(random(0, HEIGHT))), 
			((random(0,300) / 100.0) - 1.5),
			((random(0,300) / 100.0) - 1.5));
		println(_st.x, _st.y);	// printing state's variables works here

	    float _r = 1.5;
	    boolean _merged = false;

	}
}

// test instance of State works
State testState = new State(1,2,3,4);
println(testState.x,testState.y);  // works

// instance of planet 
Planet sun = new Planet();
println(sun._st);			// returns Null

Thankyou!

1 Like

Hi,

I think it is because you are creating a local variable _st inside the Planet constructor.

Try simply write:

_st = new State(
			float(int(random(0, WIDTH))), 
			float(int(random(0, HEIGHT))), 
			((random(0,300) / 100.0) - 1.5),
			((random(0,300) / 100.0) - 1.5));
2 Likes

oh yeah that worked!

thanks!