310 likes | 436 Views
Messages, Instances, and Initialization (Methods). CMPS 2143. Terms. Creation – allocation of memory space for a new object and the binding of that space to a name Initialization – setting initial data values for the object and establishing initial conditions for manipulating it
E N D
Terms • Creation – allocation of memory space for a new object and the binding of that space to a name • Initialization – setting initial data values for the object and establishing initial conditions for manipulating it • Message passing (method lookup, method call) – dynamic process of asking an object to perform a specific action.
Messages • A message is always given to some object, called the receiver • Different objects may accept the same message and yet perform different actions • eg. circle.getArea() and square.getArea() • 3 parts to a message-passing expression • aGame.displayCard (aCard, 42, 27) receiver message selector arguments
Variations in Messages Syntax • Most common syntax uses period to separate receiver from selector / some use a space • Requiring ( ) when they are empty (known as a unary message) • Messages may require keyword notations • aGamedisplayCard: aCardatLocation: 45 and: 56. • Might use brackets • int cardRank = [aCardgetRank];
Examples: • C++, C#, Java, Python, Ruby aCard.flip (); aCard.setFaceUp (true); • Pascal, Delphi, Eiffel, Oberon aCard.flip; aCard.setFaceUp(true); • Smalltalk aCard flip. aCardsetFaceUp: true. • Objective-C [aCardflip.] [aCardsetFaceUp: true]. • CLOS (flip aCard) (setFaceUpaCard true)
Statically vs Dynamically Typed Languages • IMPORTANT in regards to message passing • Java, C++, C#, and Pascal are statically typed • Use the type of the receiver to check at compile time that a receiver will understand the message selector • Smalltalk, CLOS and Python are dynamically typed • No way to do this at compile time, so may generate a run time error if receiver does not understand the message selector • Objective-C – you have a choice on a variable by variable basis
Accessing Receiver within Method • Message is ALWAYS passed to a receiver in OOP • Receiver (in most languages) does NOT appear in the arguments - it is implicit within the method • When necessary, can be explicit and use a pseudo-variable • Java, C++, C# use this • Eiffel uses Current • Smalltalk, Obj-C, Object Pascal – use self • Python, CLOS, Oberon require explicit
C++ Example of this PlayingCard::PlayingCard (Suits suitValue, int rankValue) { this.suitValue = suitValue; this.rankValue = rankValue; } • Rarely needed, unless you need to pass this to another method. • Some Java guidelines suggest this style.
Java Example class QuitButton extends Button implements ActionListener { public QuitButton ( ) { : //install ourself as a listener for button //events addActionListener (this); } : }
Creating Primitive objects • Most languages, variables created in a declaration statement – some can combine initialization • Pascal var sum : integer; begin sum := 0; • Java, C++, C# int sum = 0; • Primitive variables exist within block they are declared
Creating Objects • Usually process of naming and creating Objects separate • Java PlayingCardaCard; aCard = new PlayingCard (Heart, 3); • or PlayingCardaCard = new PlayingCard (Heart, 3);
Creating Objects • C++ - you have a choice PlayingCardaCard(Heart, 3); • or PlayingCard* aCard; aCard = new PlayingCard (Heart, 3);
Creation of Array of Objects • Create/allocate array • Create/allocate array elements • C++ - can be combined PlayingCardcardArray [52]; //all will have default values Heart, 0 • Java PlayingCardcardArray[ ] = new PlayingCard [52]; for (int i = 0; i < 13; i++) cardArray[i] = new PlayingCard (Spade, i+1); Draw Picture
Memory Allocation • All OO languages use pointers in underlying representation – not all expose this rep to the programmer • Java “has no pointers” in contrast to C++ (that is they can’t be seen by the programmer) • C++ PlayingCardaCard; //automatic variable PlayingCard * aCard = new PlayingCard; //dynamically allocated
Memory Recovery • Primitive variables are automatically recovered on procedure/method exit • Automatic variables are automatically recovered on procedure/method exit • Dynamically allocated variables are recovered • Using delete or free • Fast, but programmer could forget and create memory leaks • Automatic garbage collection • Slow, but no memory leaks and not possible to accidently try to use memory after freed or try to free memory already freed
Examples • Ojective-C [acard free]; • C++ delete aCard • Arrays • C++ delete [ ] cardArray; • Java, C#, Smalltalk, CLOS – auto garbage collection
Constructors • Constructor is a special method used to initialize a newly created object • Want to guarantee that an object can never be used before it has been initialized • Do NOT construct twice!!! • You’ll get a redefinition error or memory leak • Constructors have same name as class • Never have a return type
Example • Java declaration/definition class PlayingCard { public PlayingCard (int s, int r) { suit = s; rank = r; faceup = true; } : } • Use aCard = new PlayingCard (PlayingCard.Diamong, 3);
Overloaded Constructors • C++, C#, Java allow several methods with same name, as long as signature is different class PlayingCard { public: PlayingCard () { suit = Diamond; rank = 1; faceUp = true;} PlayingCard (Suit s, int r) { suit = s; rank = r; faceUp = true;} PlayingCard ( PlayingCard & other) { suit = other.suit; rank = other.rank; } };
Calling Constructors in C++ PlayingCardcardOne; //invokes default PlayingCard * cardTwo = new PlayingCard; //default PlayingCardcardThree (PlayingCard.Heart, 3); //param. PlayingCardcardFour (cardThree); //copy CAREFUL!!! //creates a new card PlayingCardcardFive; //forward definition for function called cardSix that //returns a PlayingCard PlayingCardcardSix (); //
Calling Constructors in Java PlayingCardcardOne = new PlayingCard(); //default PlayingCardcardTwo = new PlayingCard(); //default PlayingCardcardThree = new PlayingCard(PlayingCard.Heart, 3); //param. PlayingCardcardFour = cardThree.clone(); //copy CAREFUL!!! //only creates reference PlayingCardcardFive; //syntax error?? PlayingCardcardSix ();
Other languages • Objective-C constructors do not have to have same name, use + sign • Apple Object Pascal has none (create using new) • Delphi Pascal closer to C++ • Python uses __init__
Constant values • Data fields that can be assigned once and thereafter are not allowed to change • Constructors give us the ability to assign the values • Java – it is a final variable class ShippingCo implements IShippingCo { //max packages public final int MAX = 100; : }
Java • Final value can be assigned in the constructor (s) class Game implements IGame { public Game (int maxPlayers ) { MAXPLAYERS = maxPlayers; : } : public final int MAXPLAYERS; }
C++ • Just uses const instead • One difference between C++ and Java • C++ are truly constant • Java finals asserts that the associated variable cannot be assigned a new value – nothing prevents it from changing its own internal state final aBox = new Box(); //aBox can be assigned only //once aBox.setHeight(10); //can change internal state
Orthodox canonical class form • C++ Guidelines on Style say you should define 4 important methods • A default constructor • A copy constructor • An overloaded assignment operator • A destructor (even if it is an empty method) • We have already seen the first two
Destructors and Finalizers • Actions to perform at the end of a variable’s lifetime • Performed in C++ with a destructor easily • Invoked automatically • On block exit for automatic variables • On delete for dynamic variables • Destructor is the name of the class preceded by a tilde (~) • Has no arguments • Should always provide one, even if empty • There is a system default one
C++ class ShippingCo { public: : ~ShippingCo ( ) { delete [] items;} private: Package [ ] packages; int numPackages; int coID; }
Other languages • Delphi Pascal uses keyword destructor, called when memory is freed • Java and Eiffel have similar facilities, although both languages use garbage collection.
Java finalizer Class FinalizeExample { : public void finalize () { System.out.printline (“finally doing finalization”); System.exit (0); } Object x = new FinalizeExample (); //Superclass Object x = new Integer (3); //redefining x releases memory . : //at any point the gc will get it
Metaclasses • Hidden classes • Ha! Classes are objects • Contain static member data and static methods • To access these members ClassName.methodName (args); double y = Math.sqrt (4.4);