Sep 03, 2009

Quick Tip: Override toString();

Sometimes when making custom classes a trace of an object just isn't enough information. For instance, if I had a custom person class, a trace would probably look something like [Object Person]. A quick and easy solution is to override the objects toString() method to provide a more detailed explanation. As with all good things though, use it in moderation. There is no need for each class to spill it's guts in a simple trace. Sometimes a movieclip should just be a movieclip.

Here's some code!
package {
	import flash.display.Sprite;
	public class Main extends Sprite {
 
		public function Main() {
			var p:Person = new Person("Charlie");
			var pp:PersonPicture = new PersonPicture("Charlie.jpg");
			trace(p);	// [Person Charlie]
			trace(pp);	// [PersonPicture Charlie.jpg]
		};
	}
}
 
/**
 *	class Person
 *  Even though it's not written, Person extends the "Object" class by default.
 *  Though a toString function exists for Objects, we don't need to override here.  Just declaring it is enough.
 */
final class Person {
	private var _name:String;
 
	public function Person($name:String) {
		_name = $name;
	};
 
	public function toString():String {
		return "[Person "+_name+"]";
	};
}
 
/**
 *	class PersonPicture
 *  In the case of Sprites (and most other classes) we actually need to explicitly override the function.
 */
import flash.display.Sprite;
final class PersonPicture extends Sprite {
	private var _url:String;
 
	public function PersonPicture($url:String) {
		_url = $url;
	};
 
	override public function toString():String {
		return "[PersonPicture "+_url+"]";
	};
}

Share this Post


                           

Comments


Lily Jacks     Oct 06, 2009
Interesting tip, thanks. I'd also be quite interested to know about overriding the function...any ideas? I like the quote that everyone is creative on your page by the way, gives me some hope!

Kofi     Sep 16, 2009
what happens when you dont explicitly override the function?

Ben     Sep 04, 2009
I sometimes used a JSON class for a quick & dirty way of encoding objects to strings for tracing ;-p

MSFX     Sep 04, 2009
"Sometimes a movieclip should just be a movieclip"

Quote of the week, bless those poor little movieclips that keep losing their origins haha


Speak






Submit »