Example #1 - Rectangle


Here is the code for two static factory methods (highlighted) for a Rectangle class. Usage is also shown under "Try It".
class Rectangle {

	/** Returns new Rectangle with passed width and height */
	static fromWidthHeight(w, h) {
		return new Rectangle(w, h);
	}

	/** Returns new Rectangle that is square with width and height
	equal to passed param side */
	static fromSide(side) {
		return Rectangle.fromWidthHeight(side, side);
	}

	constructor(aWidth, aHeight) {
		this.width = aWidth;
		this.height = aHeight;
	}

	/** Return short user-friendly display string */
	toString() {
		return 'Rectangle -- ' + this.width + 'x' + this.height;
	}
}
	
//Try It
var rec, square;
rec = Rectangle.fromWidthHeight(10, 5);
square = Rectangle.fromSide(15);
println(rec.toString());
println(square.toString());



Example #2 - FullName


Here is the code for two static factory methods (highlighted) for a FullName class. Usage is also shown under "Try It".
class FullName {

	/** Returns new FullName with first, middle and last names */
	static fromFirstMiddleLast(first, middle, last) {
		return new FullName(first, middle, last);
	}

	/** Returns new FullName with first and last names
	Middle name is set to blank */
	static fromFirstLast(first, last) {
		return FullName.fromFirstMiddleLast(first, '', last);
	}

	/** Returns new FullName with first name
	Middle and last names are set to blank */
	static fromFirst(first) {
		return FullName.fromFirstMiddleLast(first, '', '');
	}

	constructor(aFirst, aMiddle, aLast) {
		this.first = aFirst;
		this.middle = aMiddle;
		this.last = aLast;
	}

	/** Return short user-friendly display string */
	toString() {
		return 'Name -- ' + this.first + ' ' + this.middle + ' ' + this.last;
	}
}
	
//Try It
var name1, name2, name3;
name1 = FullName.fromFirstMiddleLast('Asha', 'Kanvar', 'Gupta');
name2 = FullName.fromFirstLast('Asha', 'Gupta');
name3 = FullName.fromFirst('Asha');
println(name1.toString());
println(name2.toString());
println(name3.toString());