[Grace-core] Inheritance and object initialisation

Andrew P. Black black at cs.pdx.edu
Tue Jul 24 17:53:10 PDT 2012


On 20 Jul 2012, at 14:27 , Kim Bruce wrote:

> The second alternative does give more flexibility, but seems to require an early decision on the meaning of clone that would be binding on all subobjects created via inheritance.  One thing that could be done with the first semantic alternative is to simply replace "inherits a" in the code above by "inherits a.cloneMeth" where cloneMeth is some method (there may be several) creating some kind of clone for a.  Then the inheriting object could choose what kind of clone they want to use.

Neither deep copy nor shallow copy is "right".  It is easy to come up with an example where one wants the other thing.

The classic solution is that clone makes a shallow copy, and that copy is defined by default to do a clone, but can be overridden to deep copy any particular fields that the programmer wishes to deep copy.  It might be more elegant to do it the other way around, but it's clearly more efficient to make the default shallow, and to implement deep copy by a recursive shallow copy.  (Here I was wrong in the earlier discussion, when I said deep copy always.)

As to use cases, there is a very nice example of inheriting form objects in Michael's matching code, where he inherits from true and false.
The other example that we are all familiar with is when one class inherits from another.  Classes are singleton objects.  So, for example, a class 

	def theColor = object {
		method black { theColor.r(0)g(0)b(0) }
		method blue { theColor.r(0)g(0)b(1) }
		method magenta { theColor.r(1)g(0)b(1) }
		...
		method r(red)g(green)b(blue) {  object { def r = red; def g = green; def b = blue
										... 
		}
	}

that provided named colors might be extended to crate one that also provides named grey shades

	def colorsAndGreys = object {
		inherits theColor
		method darkGrey { greyScale(0.2) }
		method midGrey { greyScale(0.5) }
		method lightGrey { greyScale(0.8) }
		method greyScale(fraction) {  r(fraction)g(fraction)b(fraction) }
		...
	}

	Andrew



More information about the Grace-core mailing list