How to write Classes
by crucial [http://crucial-systems.com]
For a basic tutorial on how standard object-orientated classes
are composed, look elsewhere http://www.google.com/search?q=oop+class+tutorial.
this is more of a quick crib sheet.
Inheriting
NewClass { }
without specifying a superclass,
Object is taken as the default super.
NewClass : Superclass {
}
Methods
class methods are specified
*classMethod { arg argument;
}
within the class method, the keyword this
refers to the class.
instace methods are specified
instanceMethod { arg argument;
}
within the instance method, the keyword this
refers to the instance.
to return from the method use ^
someMethod {
^returnObject
}
multiple exit points also possible :
someMethod { arg aBoolean;
if(aBoolean,{
^someObject
},{
^someOtherObject
})
}
if no ^ is specified, the method will return the instance,
or in the case of Class methods, will return the class.
New Instance creation
Object.new will return to you a new object.
when overiding the class method .new you must
return a new object.
// this example adds no new functionality
*new {
^super.new
}
// common usage
new { arg arga,argb,argc;
^super.new.init(arga,argb,argc)
}
in this case note that super.new called the method
new on the superclass and returned a new object. subsequently
we are calling the .init method on that object, which is an
instance method.
warning: if the superclass also happened to call super.new.init
it will have expected to call the .init method defined in that
class, but instead will call the .init method of the class that
this object actually is, which is our new subclass.
// class variables are accessible within class methods
// and instance methods of any objects created.
classvar myClassvar;
var myInstanceVar;
Getter Setter
classic Smalltalk demands that variables are not accessible
outside of the class or instance. a method must be added to
explicitly give access:
NewClass : Superclass {
var myVariable;
variable {
^variable
}
variable_ { arg newValue;
variable = newValue;
}
}
these are referred to as getter and setter methods.
SC allows these methods to be easily added by adding < or >
var <accessMe, >setMe, <>accessMeOrSetMe;
you now have the methods:
someObject.accessMe;
someObject.setMe_(value);
this also allows us to say:
someObject.setMe = value;
someObject.acccessMeOrSetMe_(5);
someObject.accessMeOrSetMe.postln;
a getter or setter method created in this fashion may
be overriden in a subclass by manually writing a method
eg.
variable_ { arg newValue; variable = newValue.clip(minval,maxval) }
Tricks and Traps
If you should happen to declare a variable in a subclass and use the same name as a variable declared in a superclass, you will find that both variables exist, but only the one in the objects actual class is accessible. You should not do that.
Links to this Page
- enter. last edited on 29 January 2003 at 10:46 pm by 203.14.169.19
- Theory last edited on 2 August 2006 at 3:11 pm by Q1e64.q.pppool.de