I have the following class:
class Position {
private double x,y;
private int id;
private static int count=0; //counts number of times a Position object has been created
public Position (double initX, double initY) {
x=initX;
y=initY;
id=count;
count++;
}
public Position (Position a) {
id=count;
count++;
x=a.x;
y=a.y;
}
I want to now create a Position object in another of my .java files. How would I do so? Wouldnt I just use Position x=new Position; ? Thats not working. Do I have to import the position class into the files? I tried that too, didnt work. Wouldnt let me import. My files are in the default folder.
Here’s where I want to use it. Im not even sure Im reading the instructions correctly. Is this what they want from me? To initialize every element of the array to a new position object?
/**
* Returns an array of num positions. Each position is initialized to a random
* (x,y) position.
* if num is less than zero, just return an empty array of length 0.
*
* @param num
* number of positions to create
* @return array of newly minted Points
*/
public int[] randomPos(int[] a) {
int numPositions=Position.getNumPositionsCreated();
int[] posArr=new int[numPositions];
int x,y;
for (int i=0; i<numPositions;i++)
Position rand = new Position(x,y);
//
You would need to invoke the constructor,
Since one of your constructor takes two
double‘s as arguments, I used those as an example.Or, you could create a new
Positionobject by passing in anotherPositionobject,Also, just in case you are unsure, there is a difference between instantiation and declaration!
Instantiation:
Now,
posXis an instance of aPositionobject, because we construct our object by invoking the constructor.Declaration:
Note that the
posXvariable is declared to be aPositionobject, but has not yet been instantiated soposXwould have anullreference.Update:
Without actually do the homework for you, because you will not learn that way. I can tell you that what you have so far, and what is listed in the javadoc above do not agree. Also, given by the way the javadoc is written, it is tough to follow, therefore let me try to clean it up for you and leave you to do the rest,
Now we can break down that javadoc, so lets pinpoint what we know.
nwhich indicates how big thePositionsarray should be.nis equal to0, if so we return an emptyPositionarray.Positionobject would be instantiated with randomxandyvalues.Positionarray.This should get you started, I am sure you can figure out the rest.