Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"super" keyword in class method

I'm learning a basics of Smalltalk. There's a super keyword which is used to call a method from superclass inside a subclass method:

Object subclass: # A
   test
      ^1

A subclass: # B
   test
      ^2
   callSuper
      ^super test

So B new callSuper evaluates to 1.

OK. That's clear.

So now, I'm defining a bunch of class methods for B class:

createNew1
    ^super new
createNew2
    ^self new
create
    ^self
createSuper
    ^super

And they evaluates respectively to a B, a B, B and an error (which shows me that super is not a cast to subclass but kind of a message dispatcher).

Why am I getting instances of B class despite super keyword? And what's a difference between a B and B objects? I've started to think that the B object is a special, singletone instance (just like static attributes are implemented in other languages) of class B, but still - I've checked and it's class is a B and subclass is an A.

What is the semantics of super keyword in class methods? How it differs from semantics inside objects methods? What really is the object which can be obtained by calling self inside class method?

like image 320
Wojciech Żółtak Avatar asked Jun 03 '12 20:06

Wojciech Żółtak


2 Answers

self and super always refer to the same object, the current receiver. The only difference is that self starts the lookup of the following method send in the class of the receiver and super in the superclass of where the method is defined.

See Chapter 5 of Pharo by Example for details.

like image 177
Lukas Renggli Avatar answered Sep 21 '22 05:09

Lukas Renggli


Your answer to the first example is wrong. B new callSuper returns 1. Lukas gave you the exact definition of the semantics of super. It's basically an alias for 'self' which modifies the method lookup for the message sent to it. self message will start looking for methods in the class of the receiver, super message will start searching in the superclass of the class defining the method that contains the super message expression (so the class of the receiver isn't relevant in this case).

In your second example super new and self new end up calling the same method (defined somewhere in the Behavior hierarchy) because that's the closest method definition of new in both cases. If, however, you renamed the createNew methods to new, then new ^self new would be an infinite loop, whereas new ^super new calls the Behavior method.

like image 36
Martin Kobetic Avatar answered Sep 20 '22 05:09

Martin Kobetic