What is the Smalltalk equivalent of Java's static?

后端 未结 3 1461
忘掉有多难
忘掉有多难 2020-12-19 02:30

What is the Smalltalk equivalent of Java\'s static fields and methods? IOW, what do the Smalltalkers do when they need class level data and/or methods?

3条回答
  •  生来不讨喜
    2020-12-19 03:05

    The most important mind-shift needed if you come to Smalltalk from Java or such, is that classes are objects.

    A static in Java-like languages can have many different semantics. Usually this has to do with visibility. You need an object that is independent from any instances of a class, but you want to restrict the visibility of this object to within the class, that is: only visible from instances of the class or the class itself (in Smalltalk, because in Java classes are not first-class objects).

    In Smalltalk you usually have more options for this:

    1. Class instance variables
    2. Class variables or pool variables (depending on your Smalltalk dialect)

    A class instance variable is indeed just like an instance variable of instances of any class: the class has this property, and this can be made accessible for any instance of the class by providing a getter method on the class (not on the instances, we call this a class method). This is useful if you have default values and such. Example:

    Define a class Car, with instance variable colour, PLUS a class instance variable defaultColour (which of course would have the value "BLACK" ;-))

    Smalltalk defineClass: #Car
        superclass: #{Core.Object}
        indexedType: #none
        private: false
        instanceVariableNames: 'colour '
        classInstanceVariableNames: 'defaultColour'
        imports: ''
        category: ''
    

    This is a class definition (actually a message to the object Smalltalk) in VisualWorks Smalltalk. If you create a subclass of Car, it inherits the class instance variable defaultColour, as a normal object would do as well. If the defaultColour class instance variable has a value, the subclass also inherits this value!

提交回复
热议问题