简体   繁体   中英

“class” message sent to superclass in Smalltalk

Let us consider following classes:

Object subclass: Sup [].

Sup subclass: Sub [ print_superclass [ super class printOn: stdout. ] ].

When I try to run print_superclass method on Sub I get

> Sub new print_superclass.
Sub

I expected here to get Sup because the class call was moved back to the superclass of Sub which is Sup . Why does it behave like this?

Because super is a pseudo-variable pointing to the receiver of the message. Super and self point to the same object and have the same identity.

super == self ---> true

The difference between them is that super tells the message lookup to start searching the next in the method dictionary "above" that containing the method.

The definition is confusing, but in this case, super only says that the method search for #class does not start in Sub methods, but in Sup methods. However, it does not have effect because #class is defined in a higher level of the hierarchy and its implementation refers to the class of the receiver, that is an instance of Sub

The behavior you get is the expected one. The key is in the semantics of super . Let's see some examples before analyzing your case:

Example 1

ClassA         "implements msg"
  ClassB       "implements msg"
    ClassC     "implements msg"

This means that the inherited version of msg is overridden in ClassB and ClassC . In this case

super msg       "sent from ClassC invokes ClassB >> msg"
super msg       "sent from ClassB invokes ClassA >> msg"
super msg       "sent from ClassA will signal MessageNotUnderstood"

(I'm assuming msg is not implemented above ClassA )

Example 2

ClassA         "implements msg"
  ClassB       "does not implement msg"
    ClassC     "implements msg"

Then

super msg       "sent from ClassC invokes ClassA >> msg"
super msg       "sent from ClassB invokes ClassA >> msg"

Example 3

ClassA         "implements msg"
  ClassB       "does not implement msg"
    ClassC     "does not implement msg"

Here

super msg       "sent from ClassC invokes ClassA >> msg"
super msg       "sent from ClassB invokes ClassA >> msg"

So, the semantics of super is: start the lookup in my superclass .

Your case

Yo have

Object         "implements class"
  Sup          "does not implement class"
    Sub        "does not implement class"

Therefore, when you send super class from Sub it will invoke Object >> class , right? Which is the same as sending self class (because class is not implemented in Sub ), which is Sub . And since Sub new print_superclass sends super class from Sub , you get Sub .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM