1225
1225

Reputation: 105

In Smalltalk, how do you invoke accessor methods in Class B from within Class A on an instance of class B?

For example, in class B I have #setValue and #getValue, but I can't use these in Class A. How do I accomplish this?

edit:

what I thought would work would be ClassBInstance setValue:1. or even ClassB ClassBInstance setValue:1. but neither do.

Upvotes: 0

Views: 421

Answers (2)

Sanjay Minni
Sanjay Minni

Reputation: 56

create an instance variable in class A say instanceVariableNames: 'binstance'

in class A create the initialize method (instance side i.e. not the class side) and ensure the following code snippet is there super initialize. ... bInstance := ClassB new.

now anywhere (i.e. in any method) in ClassA use bInstance setValue: 'whatever' or myVar := bInstance getValue

BTW in Smalltalk conventionally set and get is not used ... its simply setValue is value: getValue is value note difference of the :

hope it helps

Upvotes: 3

rohit sharma
rohit sharma

Reputation: 19

Object subclass: #Foo  
    instanceVariableNames: ''  
    classVariableNames: 'e'  
    category: 'Example'

save this using ctrl+s

now generate accessors by write clicking then Refactoring->Class Var Refactoring->Accessors then a box appear accept it.
Go to class side. Modify e method as

Foo class>>e  
    e  isNil ifTrue: [ self e: 5] .  
    ^e.  

accept it.
Now again define a new class(remember to uncheck class side and go to instance side).

Object subclass: #Faa  
    instanceVariableNames: 'a'  
    classVariableNames: ''  
    category: 'Example' 

save this.
Now again generate accessors by right click on class Faa then
Refactoring -> Class Refactoring -> Generate Accessors then a box appear accept it.

Now go to Playground or Workspace run these commands

x := Faa new.   "right click on this and select doit"  
x a.            "right click on this and select print it"  
x a: Foo e.     "right click on this and select doit"  
x a.            "right click on this and select print it"  

you observe the difference in values of a variable.

Upvotes: 1

Related Questions