Presentation is loading. Please wait.

Presentation is loading. Please wait.

3C-1 Identifiers Variables Literal Objects  Numbers  Characters  Strings Control Structure  Blocks  Conditionals  Loops Messages Defining New Classes.

Similar presentations


Presentation on theme: "3C-1 Identifiers Variables Literal Objects  Numbers  Characters  Strings Control Structure  Blocks  Conditionals  Loops Messages Defining New Classes."— Presentation transcript:

1 3C-1 Identifiers Variables Literal Objects  Numbers  Characters  Strings Control Structure  Blocks  Conditionals  Loops Messages Defining New Classes Running Little Smalltalk A Small Example Squeak Essentials

2 3C-2Identifiers Variable names  Local variable: begin with a lower case letter (convention).  newName := 17 Assignment  Shared variable: begin with an upper case letter (convention).  TranscriptGlobal variable Class names  Begin with a capital letter (convention).  Integer Pseudo-variables: reserved names  self Current object  super Superclass  true Instance of True  false Instance of False  nil Instance of UndefinedObject  thisContext the top frame of the run-time stack  Method arguments  Block arguments

3 3C-3 Kinds of Variables Global Variables: live forever.  X := 2 Local Variables: defined in blocks/methods Live as long as needed. Often, obey call stack semantics.  Temporary Variables  Actual Parameters  Example: findSkill: aSkill | empsWithSkill | empsWithSkill := Set new. … ^empsWithSkill. Instance Variables: defined in a class definition. One copy per class instance. Live as long as the instance (also a variable) lives. Object subclass: #Color instanceVariableNames: 'rgb cachedDepth …' classVariableNames: '…'

4 3C-4 Kinds of Variables – Cont. Class Variables: Shared among all the instances of a class. Live as long as the class lives. Object subclass: #Color instanceVariableNames: '…' classVariableNames: '…ColorNames…' Pool Variables: Shared between several classes that may not be related by inheritance. Not a good practice – try to avoid them ArrayedCollection subclass: #Text instanceVariableNames: 'string runs' classVariableNames: '' poolDictionaries: 'TextConstants' category: 'Collections--Text'

5 3C-5 Self and Super self indicates the current object itself, for  re-sending  return super indicates the sub-object, i.e., the object corresponding to the super class. Used for  Refining an overridden method: Example: suppose that class Manager inherits from class Employee. Then, every manager has an employee part in it: Super Self

6 3C-6 Literal Objects Integer  7 Uniquely identified by its name, need not be declared Float  -3.14 Char  $A$9$$ String Subclass of ArrayedCollection  'a string' Array  #(this is an array)  #(12 'abc' (another one))  {1. 2. 1+2} Symbol  #aSymbol

7 3C-7Numbers May be Integer ( 1, -3 ), Float ( 0.25, 3.5e-2 ) or Fraction ( 1/4, -3/5 ) Recognise arithmetic messages: + - * / Recognise comparison messages: = = ~= Quotient and remainder: quo: rem: Bitwise logical operations: bitAnd: bitInvert: bitOr: bitXor: bitShift: Other messages: positive, negative, strictlyPositive, squared, sqrt, lcm:, gcd:, abs, truncated, rounded, ceiling, floor...

8 3C-8Characters Characters are written with a preceding dollar sign. Recognise comparison messages: = = ~= asInteger returns the numeric character code corresponding to the receiver. asString returns a string of length 1 corresponding to the receiver. isAlphaNumeric, isDigit, isLowercase, isUppercase return true if the receiver satisfies the condition, and false otherwise.

9 3C-9Strings Are sequences of characters enclosed by single apostrophes. Recognise comparison messages: = = ~= Concatenation:, Change: at:put: Substring: copyFrom:to:

10 3C-10 Summary: Basic Objects In Smalltalk, several objects may be uniquely identified by literals. Some examples are: Number : 1 3.14 -10 0.27e-2 Character: $a $& $$ String : 'Hello, world!' '9 o''clock' Array : #('cat' 'dog' 'cow') #( (1 0) (0 1) ) Boolean : true false Block : [ :name | name print ] [ i := i + 1 ] Other basic objects may be obtained by sending messages to these literals: Fraction : Returned by the message / to an Integer. Examples 1/5 -2/3 Interval : Returned by the message to:by: to a Number. Example 1 to:5 by:2 returns Interval( 1 3 5 )

11 3C-11Blocks A block has the general form: [arguments | statements]  Enclosed in surrounding square braces.  Encapsulates a sequence of Smalltalk statements.  [ Transcript show:'hello’]  Several statements are separated by dots.  [ i := i + 1. Transcript show: i]  Executes only when received a message value.  [ i := i + 1. Transcript show: i] value  May have arguments.  [ :x :y | Transcript show:(x + y)] value: 2 value: 3  Arguments are local. Methods are actually blocks.

12 3C-12 Blocks as First Class Citizens May be stored in variables May be returned from procedures Example  Twice := [:x | 2 * x]  Twice value: 10  20  Twice value: 5  10 Executes in the context in which it was defined. b := [ i <- i + 1. Transcript show: i]... b value The identifier i above refers to the binding known at the time the block was defined. Capitalized Twice is acceptable, since it is a global variable.

13 3C-13 Control Structures Blocks are useful for several control structures:  anInteger timesRepeat: aBlock  anArray do: aBlock  anInterval do: aBlock  aBoolean ifTrue: aTrueBlock ifFalse: aFalseBlock  aBlock whileTrue: anotherBlock Examples:  5 timesRepeat: [Transcript show: 'Hello, world!‘; cr]  #(85 80 75) do: [ :grade | sum := sum + grade ]  ( 0 to: 10 by: 2 ) do: [ :i | Transcript show: i squared; cr]  0 positive ifTrue: [Transcript show:'0 is positive‘; cr]  [ count <= max ] whileTrue: [Transcript show: count;cr. count := count+1]

14 3C-14 Passing Messages All actions are produced by passing messages.  A message is a request for an object to perform some operation.  A message can contain certain argument values. The behaviour of an object in response to a specific message is dictated by the object ’ s class.  An object is an instance of a larger class (category) of objects. The list of statements that define how an instance of some class will respond to a message is called the method for that message.

15 3C-15 Message Types Messages have the general form: receiver selector arguments Unary messages  Formed by a single word, requires no arguments. 7 sign Yields 1 7 factorial sqrt Evaluated from left to right: sqrt(7!) Binary messages  Formed from one or two adjacent nonalphabetic characters, a single argument is required. 7 + 4 Yields 11 7 + 4 * 3 Yields 33 7 + 17 sqrt Unary message has a higher precedence Keyword messages  Consists of one or more keywords (an identifier followed by a colon), each keyword requires an argument. 7 max: 14 7 between: 2 sqrt and: 4 + 2

16 3C-16 Messages ’ Precedence Unary messages have precedence over binary messages, that have precedence over keyword messages. > 4 squared + 1 negated gcd: 3 factorial 3 Parentheses may be used to change precedence. > ( 4 squared + 1 negated gcd: 3 ) factorial 6 Keyword messages can not be combined. > 100 quo: 5 rem: 3 ERROR: SmallInteger does not understand message #quo:rem: Keyword messages can be separated by parentheses. > ( 100 quo: 5 ) rem: 3 2

17 3C-17Cascades The character ; may be used to send several messages to the same object. The receiver of all cascaded messages is the receiver of the first message involved in a cascade The value returned by a cascade of messages is the value of the last cascaded message Examples: > 2+2; * 1000; squared; factorial; sqrt 1.414213562373095 > ( 'Smalltalk' copyFrom:1 to:5 ) size 5 > 'Smalltalk' copyFrom:1 to:5; size 9 > 'Smalltalk' at:4 put:$r; at:5 put:$t;asString Smarttalk  Why wasn ’ t the answer Smarltalk ?!?

18 3C-18 Defining the Class Point2D * File point2D.st Object subclass: #Point2D instanceVariableNames: 'xCoord yCoord’ classVariableNames: ‘’ poolDictionaries: ‘’ category: 'Point'! initialize xCoord := 0. yCoord := 0 ! x: newX xCoord := newX ! y: newY yCoord := newY ! x: newX y: newY self x: newX. self y: newY !

19 3C-19 The Class Point2D (cont.) x ^xCoord ! y ^yCoord ! ! distanceTo: aPoint ^ ( ( xCoord - aPoint x ) squared + ( yCoord - aPoint y ) squared ) sqrt ! ! printString ^'( ', xCoord printString, ', ', yCoord printString, ' )'

20 3C-20 Using the Class Point2D > (Point2D methodDict keys) do: [:x | Transcript show: x asString; show: ‘ ’] distanceTo: initialize y x: printString x:y: y: x > origin := Point2D new ( 0, 0 ) > aPoint := Point2D new. > aPoint x: 3; y: 4 ( 3, 4 ) > aPoint x + aPoint y 7 > aPoint distanceTo: origin 5.0

21 3C-21 Manipulating a Point p := Point new  Assigns to p an object of class Point p x: 3 y: 4  Sends the point object p a keyword message x:y: p x  Sends the point object p an unary message x  The object returns as a result the object 3 p rho  Sends the point object p an unary message rho  The object returns as a result the object 5  Oops, but rho is not defined yet...

22 3C-22 Adding Methods to Class Point2D rho: dist theta: angle xCoord := dist * angle cos. yCoord := dist * angle sin ! rho ^ (xCoord squared + yCoord squared) sqrt ! theta ^ (yCoord / xCoord) arcTan

23 3C-23 Summary of Main Points Objects  Everything is an object.  Each object is an instance of a class.  Instance variables are private. Messages  All actions are produced by passing messages.  A message activates a method. Methods  A method has a signature (selector & arguments) that defines how it is to be used.  ^exp returns the value of exp (an object) as the result.


Download ppt "3C-1 Identifiers Variables Literal Objects  Numbers  Characters  Strings Control Structure  Blocks  Conditionals  Loops Messages Defining New Classes."

Similar presentations


Ads by Google