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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With