constructor as helper in clone method implementation

Hi,

if you wanted to implement the clone method to create duplicates of your class you certainly face the problem in extending class where you had to duplicate the code just because the new instance should be type of the child and not parent (base) type.

package examples
{
	public class A
	{
		protected var m_sPropA:String = "Prop A";
		public function A()
		{}
		
		public function get propA():String
		{
			return m_sPropA;
		}
		public function set propA(value:String):void
		{
			m_sPropA = value;
		}

		public function clone():A
		{
			var copy:A = new A();
			
			copy.propA = propA;
			
			return copy;
		}
	}
}

and another class inheriting from it

package examples
{
	public class B extends A
	{
		protected var m_sPropB:String = "Prop B";
		public function B()
		{}
		
		public function get propB():String
		{
			return m_sPropB;
		}
		public function set propB(value:String):void
		{
			m_sPropB = value;
		}
		
		override public function clone():A
		{
			//you can't initiate A as it will not have propB - so you have to re write entire method duplicating whatever original method was setting (e.g. propA)
			var copy:B = new B();
			
			copy.propA = propA;
			copy.propB = propB;
			
			return copy;
		}
	}
}

From this example, I hope you can see that when there are more classes in the chain it may be more tricky to update and prone to error, but with the constructor property you can simplify it greatly, see revised code:

package examples
{
	public class A
	{
		protected var m_sPropA:String = "Prop A";
		public function A()
		{}
		
		public function get propA():String
		{
			return m_sPropA;
		}
		public function set propA(value:String):void
		{
			m_sPropA = value;
		}
		
		public function clone():A
		{
			var copy:A = new (this as Object).constructor();//the change
			
			copy.propA = propA;
			
			return copy;
		}
	}
}
package examples
{
	public class B extends A
	{
		protected var m_sPropB:String = "Prop B";
		public function B()
		{}
		
		public function get propB():String
		{
			return m_sPropB;
		}
		public function set propB(value:String):void
		{
			m_sPropB = value;
		}
		
		override public function clone():A
		{
			var copy:B = super.clone() as B;//the change
			
			copy.propB = propB;
			
			return copy;
		}
	}
}

so all we need to implement in the clone is just those parts that are relevant to the implementing class:-)
best regards

2 thoughts on “constructor as helper in clone method implementation

  1. I love your code lukasz, even i learned as3 from your code, but now i will not get change to view your code (i left redtray),so this blog is my last hope,

    this example is perfect but it should have setter in last examples for propA and propB , because we are setting its value by doing “copy.propB = propB;” am i wrong

    thanks again lukasz