Instances and Initialization

advertisement
Messages, Instances, and
Initialization (Methods)
CMPS 2143
2
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.
3
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
4
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
▫ aGame displayCard: aCard atLocation: 45 and: 56.
• Might use brackets
▫ int cardRank = [aCard getRank];
5
Examples:
• C++, C#, Java, Python, Ruby
aCard.flip ();
aCard.setFaceUp (true);
• Pascal, Delphi, Eiffel, Oberon
aCard.flip;
aCard.setFaceUp (true);
• Smalltalk
aCard flip.
aCard setFaceUp: true.
• Objective-C
[aCard flip.]
[aCard setFaceUp: true].
• CLOS
(flip aCard)
(setFaceUp aCard true)
6
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
7
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 pseudovariable
▫ Java, C++, C# use this
▫ Eiffel uses Current
▫ Smalltalk, Obj-C, Object Pascal – use self
▫ Python, CLOS, Oberon require explicit
8
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.
9
Java Example
class QuitButton extends Button
implements ActionListener {
public QuitButton ( ) {
:
//install ourself as a listener for button
//events
addActionListener (this);
}
:
}
10
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
11
Creating Objects
• Usually process of naming and creating Objects separate
• Java
PlayingCard aCard;
aCard = new PlayingCard (Heart, 3);
• or
PlayingCard aCard = new PlayingCard (Heart, 3);
12
Creating Objects
• C++ - you have a choice
PlayingCard aCard(Heart, 3);
• or
PlayingCard * aCard;
aCard = new PlayingCard (Heart, 3);
13
Creation of Array of Objects
• Create/allocate array
• Create/allocate array elements
• C++ - can be combined
PlayingCard cardArray [52];
//all will have default values
Heart, 0
• Java
PlayingCard cardArray[ ] = new PlayingCard [52];
for (int i = 0; i < 13; i++)
cardArray[i] = new PlayingCard (Spade, i+1);
Draw Picture
14
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++
PlayingCard aCard;
//automatic variable
PlayingCard * aCard = new PlayingCard;
//dynamically allocated
15
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
16
Examples
• Ojective-C [acard free];
• C++ delete aCard
• Arrays
▫ C++ delete [ ] cardArray;
• Java, C#, Smalltalk, CLOS – auto garbage collection
17
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
18
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);
19
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; }
};
20
Calling Constructors in C++
PlayingCard
PlayingCard
PlayingCard
PlayingCard
cardOne;
//invokes default
* cardTwo = new PlayingCard; //default
cardThree (PlayingCard.Heart, 3); //param.
cardFour (cardThree); //copy
CAREFUL!!!
//creates a new card
PlayingCard cardFive;
//forward definition for function called cardSix that
//returns a PlayingCard
PlayingCard cardSix (); //
21
Calling Constructors in Java
PlayingCard cardOne = new PlayingCard();
//default
PlayingCard cardTwo = new PlayingCard();
//default
PlayingCard cardThree = new
PlayingCard(PlayingCard.Heart, 3); //param.
PlayingCard cardFour = cardThree.clone();
//copy
CAREFUL!!!
//only creates reference
PlayingCard cardFive;
//syntax error??
PlayingCard cardSix ();
22
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__
23
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;
:
}
24
Java
• Final value can be assigned in the constructor (s)
class Game implements IGame {
public Game (int maxPlayers )
{
MAXPLAYERS = maxPlayers;
:
}
:
public final int MAXPLAYERS;
}
25
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
26
Orthodox canonical class form
• C++ Guidelines on Style say you should define 4
important methods
1.
2.
3.
4.
•
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
27
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
28
C++
class ShippingCo {
public:
:
~ShippingCo ( ) { delete [] items;}
private:
Package [ ] packages;
int numPackages;
int coID;
}
29
Other languages
• Delphi Pascal uses keyword destructor, called when
memory is freed
• Java and Eiffel have similar facilities, although both
languages use garbage collection.
30
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
31
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);
Download