Object Oriented Programming

Assignment

Read the beginning of chapter 14.

Re-write any of your programs from earlier this semester in 
object oriented form, or do the following :

Create objects Square and Triangle, both of which are a Shape,
with methods to 
 (a) place them somewhere, 
 (b) change/get their color, 
 (c) draw all of them in a picture,
 (d) give a descriptive string, e.g. "rectangle with corners ... "
    
With this structure in place, one could then do something like
    one = new[Triangle, {0,0}, {0,1}, {1,0}];
    setColor[one, "blue"];
    two = new[Square, {2,2},{2,3},{3,2},{3,3}];
    setColor[three, "green"];
    Print[ describe[one]];
    Print[ describe[two]];
    drawThem[ {one, two} ]

Scratch

This is how you import the definitions needed to make this work.  First, be in a directory where you can see the CSM folder, 
which has Classes.m in it.

Directory[]

SetDirectory["Desktop"];

Then issue this command.

Needs["CSM`Classes`"]

Now we can define classes using a syntax like this.

Class[Account, Object,
	{balance,owner},
	{
		{new,
			Function[{bal,own},new[super];balance=bal;owner=own]},
		{Balance,
			Function[{},balance]},
		{Deposit,
			Function[{amt},balance+=amt]},
		{Withdraw,
			Function[{amt},balance-=amt]},
		{Owner,
			Function[{},owner]}
	}];

Class[SavingsAccount, Account,
	{},
	{
		{Withdraw,
			Function[{amt},
				If[Balance[self]<amt,
				Message[Account::nomoney,Balance[self],amt],
				Withdraw[super,amt]]]}
	}];

Account::nomoney="Balance `1` insufficient for withdrawal of `2`.";

?new

a = new[Account, 100, "John Smith"]

FullForm[a]

Methods[a]

Balance[a]

Deposit[a, 20]

Balance[a]

InstanceVariables[a]

Owner[a]

SuperClass[a]

Methods[Object]

An animal class

Class[Animal,  
        Object,  
{name, says, 
          color}, 
{{new,  
            Function[{n, s},  new[super];  name = n;  
              says = s]}, 
{Says,  
            Function[{},  says]}, 
{Name,  
            Function[{}, name]}, 
{setColor, 
            Function[{c}, color = c]}, 
{Color, 
            Function[{}, 
              color]}
}];

Methods[Animal]

Class[Cow, 
        Animal, 
{}, 
{{new,  
            Function[{}, 
              new[super, "cow", "moo"]]}
}];

Methods[Cow]

c = new[Cow];

Says[c]

Name[c]

\(\(Class[Horse, \ 
        Animal, 
{}, 
{{new, \ 
            Function[{}, 
              new[super, "horse", "neigh"]]}
}];\)\)

isa[c, Animal]

isa[c, Cow]

setColor[c, "brown"]

Color[c]

h = new[Horse];

setColor[h, "black"]

bessie = new[Cow];
setColor[bessie, "spotted"];

farm  =  {c, h, bessie};

Map[Says, farm]

Map[Color, farm]

isa[bessie, Cow]

isa[h,  Cow]