Basic Smalltalk Subclass

2019-08-07 03:45发布

问题:

I am trying to create an extremely simple Vector class as a subclass of Array in Smalltalk. My code to create the class looks like this:

Array subclass: #Vector
Vector comment: 'I represent a Vector of integers'

Vector class extend [
new [
    | r |
    <category: 'instance creation'>
    r := super new.
    r init.
    ^r 
    ]
 ]

Vector extend [
init [
    <category: 'initialization'>
    ]
 ]

Obviously I haven't written any methods yet, but I'm just trying to get this part working first. After the class is created as above, if I type: v := Vector new: 4 I get error:

Object: Vector error: should not be implemented in this class, use #new instead
SystemExceptions.WrongMessageSent(Exception)>>signal (ExcHandling.st:254)
SystemExceptions.WrongMessageSent class>>signalOn:useInstead: (SysExcept.st:1219)
Vector class(Behavior)>>new: (Builtins.st:70)
UndefinedObject>>executeStatements (a String:1)
nil

I had assumed that since it is a subclass of Array, I could create a Vector in this manner. What is the best way to go about doing this? Thanks!

Edit -- I figured it out. After reading deeper into the tutorial, I found I needed to include <shape: #pointer>

回答1:

Array is a special kind of class that has indexable instances of different lengths.

In GNU Smalltalk (which you appear to be using) the Array class is declared as:

ArrayedCollection subclass: Array [       
    <shape: #pointer>

To inherit this behaviour you can use:

Array subclass: Vector [<shape: #inherit>]

But in most cases it makes more sense to make a class that encapsulate an Array rather than a class that inherits from Array.

It's also worth pointing out that OrderedCollection is the Smalltalk equivalent of the vector container from C++ and Java.