PDA

View Full Version : OOP question, class instance id's



solconnection
January 26th, 2010, 08:40 PM
Say i have a class MyClass() with private int '_id' which is set on construction

currently i have _id a required variable on instantiation

ie.
var myInstance:MyClass = new MyClass(2);

which seems kind of ugly.
is there a way to write my class so i can instantiate it like this:

ie.
var myInstance:Myclass = new MyClass();

and the _id value is set internally and incremented for each instance of the class instantiated. I seem to remember something like this was possible, but i can't remember what it is called, and if it is bad practice or not?

thanks for your help, this forum has been a life saver lately
-Dan

IQAndreas
January 26th, 2010, 08:56 PM
Try something along these lines, and I would recommend looking into using "static" properties and methods as they can become very convenient at times!

class MyClass
{
public function MyClass()
{
_id = MyClass.nextID;
MyClass.nextID += 1;

trace("New class with id " + _id + " was successfully created!");
}

private var _id:int;

public function getID()
{
trace("This current classes' id is " + _id);
}

//Static values
private static var nextID:int = 1;

}


This is very similar, but will automatically update the nextID increment. This method works just as well, but looks a little bit nicer. A bonus is that for example if you want to update the id number by 3 instead of by 1 with each instance, just change that in the "getNextID()" function.

class MyClass
{
public function MyClass()
{
//This way looks a little nicer
_id = MyClass.getNextID();

trace("New class with id " + _id + " was successfully created!");
}

private var _id:int;

public function getID()
{
trace("This current classes' id is " + _id);
}

//Static values
private static var nextID:int = 0;
public static function getNextID():int
{
nextID += 1;
return nextID;
}

}

Krilnon
January 26th, 2010, 08:57 PM
Sure, it's possible:
for(var i:int = 0; i < 6; i++){
trace(new MyClass());
}

/*
[object MyString 0]
[object MyString 1]
[object MyString 2]
[object MyString 3]
[object MyString 4]
[object MyString 5]
*/

package {
public class MyClass {
private static var _nextID:int;
private var _id:int;

public function MyClass(){
_id = _nextID++;
}

public function toString(){
return '[object MyString ' + _id + ']';
}
}
}

It seems like a fine practice as long as you have some use for the ID.

Edit: Oh hey, IqAndreas got here first. Our code looks suspiciously similar! :P

solconnection
January 26th, 2010, 08:58 PM
you guys are wonderful, thank you both! :) very helpful answers. 'static' is the keyword i was forgetting. appreciate the code examples
-Dan