This site requires JavaScript, please enable it in your browser!
Greenfoot back
Newbie
Newbie wrote ...

2015/12/23

saving a parameter of a method of a class as a variable of another class?

Newbie Newbie

2015/12/23

#
I was wondering if it was possible to have a method called createSubjects with an int as the parameter implemented in the world's code. It is supposed to make new objects of Subject.class. I added a Method with an int as a parameter to the code of Subject.class. This int is supposed to be different for every Subject created. Would it be possible to have an int as a parameter of the createSubjects method, which is saved as a variable and can then be used as the parameter for the object's method? I hope you get what I mean :D
danpost danpost

2015/12/23

#
I think what you are wanting to do is basically give an identification number to each Subject object created. This is something that should be done in the Subject class. By using a class field (one declared as 'static'), you can keep track of how many object have been created from the class:
1
2
3
4
5
6
7
8
9
10
11
// class field
public static int objectsCreated;
 
// instance field
public int serialNumber;
 
// constructor
public Subject()
{
    serialNumber = objectsCreated;
    objectsCreated++;
The class value needs to be reset to zero when a new World object is created. So, in your World subclass constructor, add the following line before creating any Subject objects:
1
Subject.objectsCreated = 0;
As far as having the variable ( 'serialNumber' ) "used as the parameter for the object's method" -- if the methods are within the Subject class, then the parameter is not needed; method within the class have direct access to the variable. By the way, it is possible to do it the way you suggested above; however, the way I give here will avoid any complications if you add more Subject objects from elsewhere.
Newbie Newbie

2015/12/23

#
thank you for your quick reply, I'll try out your suggestion tomorrow and report back to you, if any problems occur!
Newbie Newbie

2015/12/24

#
Thank you very much indeed, it worked out exactly the way I wanted it to!
You need to login to post a reply.